Search code examples
phpmultidimensional-arrayrecursiveiterator

PHP RecursiveIteratorIterator not outputting all keys


I have the following multidimensional array:

$array = array(
  1 => null,
  2 => array(
    3 => null,
    4 => array(
      5 => null,
    ),
    6 => array(
      7 => null,
    ),
  )
);

If I use the following code to iterate over the array

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array));
foreach ($iterator as $key => $value) {
  echo $key.' ';
}        

it only outputs the keys with no arrays assigned to them. I.e.

1 3 5 7

How can I get it to include all of the keys?


Solution

  • You just need to set the mode right. From the manual:

    RecursiveIteratorIterator::SELF_FIRST - Lists leaves and parents in iteration with parents coming first.

    $iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)
                                              , RecursiveIteratorIterator::SELF_FIRST);