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. ];
  14.  
  15. $accountFieldsToRemove = [
  16.     'first_name',
  17.     'last_name',
  18.     'mail',
  19.     'name',
  20. ];
  21.  
  22. $iterator = new RecursiveArrayIterator($hit);
  23. traverseArray($accountFieldsToRemove, $iterator);
  24. print_r($iterator);
  25.  
  26. function traverseArray(array $accountFieldsToRemove, RecursiveArrayIterator $iterator)
  27.     {
  28.         while ($iterator->valid()) {
  29.             if ($iterator->hasChildren()) {
  30.                 traverseArray($accountFieldsToRemove, $iterator->getChildren());
  31.             } else {
  32.                 if (in_array($iterator->key(), $accountFieldsToRemove)) {
  33.                     echo "#{$iterator->key()} - {$iterator->current()}\r\n";
  34.                     //$iterator->offsetUnset($iterator->key());
  35.                 }
  36.             }
  37.             $iterator->next();
  38.         }
  39.     }
  40.  
File Description
  • RecursiveArrayIterator
  • PHP Code
  • 23 Sep-2022
  • 1.01 Kb
You can Share it: