iterator_to_array截断输出

时间:2012-12-21 10:10:31

标签: php iterator spl

FROM PHP DOC

  

iterator_to_array - 将迭代器复制到数组中   array iterator_to_array(Traversable $ iterator [,bool $ use_keys = true])

它适用于所有Traversable接口,但为什么我在以下代码中输入错误:

$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

但是

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

输出

1234567

See online Demo

1 个答案:

答案 0 :(得分:4)

这是因为默认情况下$use_keys为真(从5.1开始),在数组键被展平时会破坏它们。您需要禁用以下设置:

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

如果您正在运行PHP< 5.2.1你基本上搞砸了; - )