简体   繁体   中英

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. Ie

1 3 5 7

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

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)
                                          );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM