3

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

我不明白为什么我会陷入无限循环

这个脚本的逻辑是:

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

4 回答 4

7

因为您永远不会在迭代器中移动(使用 ArrayIterator::next())。

while ($it->valid()) {
    ...
    $it->next();
}
于 2012-10-03T13:31:57.737 回答
3

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

于 2012-10-03T13:32:05.697 回答
2

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

于 2012-10-03T13:33:46.780 回答
1

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

你应该使用RecursiveArrayIteratorandRecursiveIteratorIterator因为你正在处理多维数组

要获取所有值,请尝试:

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

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

于 2012-10-03T13:33:10.223 回答