2

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?

1 Answer 1

6

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);
Sign up to request clarification or add additional context in comments.

2 Comments

SELF_FIRST and CHILD_FIRST modes will both give the non-leaf items (in your case, the arrays), whereas the default LEAVES_ONLY mode does not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.