duanmu5641 2012-12-21 10:10
浏览 26
已采纳

iterator_to_array截断输出

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条回答 默认 最新

  • doufulian4076 2012-12-21 10:40
    关注

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 android报错 brut.common.BrutException: could not exec (exit code = 1)
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA
  • ¥20 csv格式数据集预处理及模型选择
  • ¥15 部分网页页面无法显示!
  • ¥15 怎样解决power bi 中设置管理聚合,详细信息表和详细信息列显示灰色,而不能选择相应的内容呢?