RecursiveArrayIterator - PHP Online

Form of PHP Sandbox

Enter Your PHP code here for testing/debugging in the Online PHP Sandbox. As in the usual PHP files, you can also add HTML, but do not forget to add the tag <?php in the places where the PHP script should be executed.



Your result can be seen below.

Result of php executing





Full code of RecursiveArrayIterator.php

  1. <?php
  2.  
  3. $hit = [
  4.     '_source' => [
  5.         'account' => [
  6.             'id'         => 123,
  7.             'first_name' => 'Foo',
  8.             'last_name'  => 'Bar',
  9.             'mail'       => 'for@bar',
  10.             'name'       => 'Foo Bar',
  11.         ],
  12.     ],
  13.     '_source2' => [
  14.         'account2' => [
  15.             'id2'         => 456,
  16.             'first_name2' => 'Foo',
  17.             'last_name2'  => 'Bar',
  18.             'mail2'       => 'for@bar',
  19.             'name2'       => 'Foo Bar',
  20.         ],
  21.     ],
  22. ];
  23.  
  24. $accountFieldsToRemove = [
  25.     'first_name',
  26.     'last_name',
  27.     'mail',
  28.     'name',
  29. ];
  30.  
  31. $iterator = new RecursiveArrayIterator($hit);
  32. traverseArray($accountFieldsToRemove, $iterator);
  33. print_r($iterator);
  34.  
  35. function traverseArray(array $accountFieldsToRemove, RecursiveArrayIterator $iterator)
  36.     {
  37.         while ($iterator->valid()) {
  38.             if ($iterator->hasChildren()) {
  39.                 traverseArray($accountFieldsToRemove, $iterator->getChildren());
  40.             } else {
  41.                 if (in_array($iterator->key(), $accountFieldsToRemove)) {
  42.                     echo "#{$iterator->key()} - {$iterator->current()}\r\n";
  43.                     // $iterator->offsetUnset($iterator->key());
  44.                 }
  45.             }
  46.             $iterator->next();
  47.         }
  48.     }
  49.  
File Description
  • RecursiveArrayIterator
  • PHP Code
  • 23 Sep-2022
  • 1.26 Kb
You can Share it: