Question

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

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top