PHP RecursiveIteratorIterator 未输出所有键

PHP RecursiveIteratorIterator not outputting all keys

我有以下多维数组:

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

如果我使用下面的代码遍历数组

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

它只输出没有分配数组的键。即

1 3 5 7

如何让它包含所有密钥?

你只需要设置正确的模式。来自 manual:

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

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($array)
                                          <b>, RecursiveIteratorIterator::SELF_FIRST</b>);