【问题标题】:Why iterating over ArrayIterator ending with endless loop?为什么迭代 ArrayIterator 以无限循环结束?
【发布时间】:2012-09-24 10:38:23
【问题描述】:

我的代码中的数组很大,所以我将它粘贴到 pastebin 中。 http://pastebin.com/6tviT2Xj

我不明白为什么会出现无限循环

这个脚本的逻辑是:

$it = new ArrayIterator($options);
while($it->valid()) {
    print $it->key();
    print $it->current();
}

【问题讨论】:

  • 在使用迭代器时不使用foreach 看起来很像 PHP3... ;)
  • 是的,但我必须知道下一个元素。
  • 无论如何我都忘记了 next() 的耻辱:P
  • 你应该使用 foreach。性能比while好。更不容易出错,就像你演示的那样。
  • @Sven - 你有什么基准来证明你声称的更好的性能吗?

标签: php infinite-loop arrayiterator


【解决方案1】:

因为你永远不会在你的迭代器中移动 (with ArrayIterator::next())。

while ($it->valid()) {
    ...
    $it->next();
}

【讨论】:

  • Just Curios .. 你测试过这段代码吗??? .. 如果你这样做了,你就会知道它有错误
  • @Baba - 不,我刚刚添加了$it->next() - 因为这是问题的原因。你的意思是什么错误?
  • 刚刚用正确的格式编辑了你的代码..你可以看到差异
【解决方案2】:

你应该使用$it->next(); 否则你将永远在同一个键上循环

【讨论】:

    【解决方案3】:

    您正在迭代当前元素,您需要执行 $it->next(); 以指向/转到下一个元素

    【讨论】:

      【解决方案4】:

      主要问题是没有在你的中使用$it->next();,但仍然有很多没有给你想要的输出,因为如果你运行print $it->current();,它只会返回Array,因为你不能用print输出数组信息。

      您应该使用RecursiveArrayIteratorRecursiveIteratorIterator,因为您正在处理多维数组

      要获取所有值,请尝试:

      $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($options));
      foreach ( $it as $key => $val ) {
          echo $key . ":" . $val . "\n";
      }
      

      查看完整演示:http://codepad.viper-7.com/UqF18q

      【讨论】:

        猜你喜欢
        • 2020-09-01
        • 1970-01-01
        • 2021-07-12
        • 1970-01-01
        • 1970-01-01
        • 2014-10-31
        • 2023-03-20
        • 2018-04-13
        • 1970-01-01
        相关资源
        最近更新 更多