4

FROM PHP DOC

iterator_to_array — Copy the iterator into an array
array iterator_to_array ( Traversable $iterator [, bool $use_keys = true ] )

It would work with all Traversable Interface but why am i getting wrong input in the following code:

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


$it =  new RecursiveIteratorIterator(new RecursiveArrayIterator($data));

echo PHP_EOL, iterator_count($it); // 7  total correct
echo PHP_EOL, implode(iterator_to_array($it));  //745  instead of 1234567 
echo PHP_EOL, implode(iterator_to_array($it, true)); //745  instead of 1234567

But

foreach($it as $v)
{
    echo $v ;
}

Output

1234567

See online Demo

1
  • I see you're trying to use RecursiveArrayIterator, you should totally drop that and use array_walk_recursive() instead =D Commented Dec 21, 2012 at 10:21

1 Answer 1

4

This is because $use_keys is true by default (since 5.1), clobbering your array keys as it's being flattened. You need to disable the setting like this:

print_r(iterator_to_array($it, false));
//                             ^^^^^

If you're running PHP < 5.2.1 you're basically screwed ;-)

Sign up to request clarification or add additional context in comments.

Comments

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.