1

我正在尝试解决如何连续循环遍历数组,但显然 usingforeach不起作用,因为它适用于数组的副本或类似的东西。

我试过了:

$amount = count($stuff);
$last_key = $amount - 1;

foreach ($stuff as $key => $val) {

    // Do stuff

    if ($key == $last_key) {
        // Reset array cursor so we can loop through it again...
        reset($stuff);
    }

}

但显然这并没有奏效。我在这里有什么选择?

4

6 回答 6

4

一种简单的方法是将ArrayIteratorInfiniteIterator结合起来。

$infinite = new InfiniteIterator(new ArrayIterator($array));
foreach ($infinite as $key => $val) {
    // ...
}
于 2013-10-18T16:58:06.087 回答
4

您可以通过while循环来完成此操作:

while (list($key, $value) = each($stuff)) {
    // code
    if ($key == $last_key) {
        reset($stuff); 
    }
}
于 2013-10-18T16:58:14.333 回答
3

这个循环永远不会停止:

while(true) {
    // do something
}

如有必要,您可以像这样中断循环:

while(true) {
    // do something
    if($arbitraryBreakCondition === true) {
        break;
    }
}
于 2013-10-18T16:56:43.477 回答
3

这是一个使用 reset() 和 next() 的方法:

$total_count = 12;
$items = array(1, 2, 3, 4);

$value = reset($items);
echo $value;
for ($j = 1; $j < $total_count; $j++) {
    $value = ($next = next($items)) ? $next : reset($items);
    echo ", $value";
};

输出:

1, 2, 3, 4, 1, 2, 3, 4, 1, 2, 3, 4

我很惊讶地发现没有这样的本机功能。这是笛卡尔积的构建块。

于 2019-09-20T18:06:32.040 回答
1

您可以使用for循环并设置一个始终为真的条件 - 例如:

$amount = count($stuff);
$last_key = $amount - 1;

for($key=0;1;$key++)
{
    // Do stuff
    echo $stuff[$key];

    if ($key == $last_key) {
        // Reset array cursor so we can loop through it again...
        $key= -1;
    }


}

显然,正如其他人所指出的那样 - 确保在运行之前有一些东西可以停止循环!

于 2013-10-18T16:57:55.547 回答
0

使用函数并在 while 循环中返回 false:

function stuff($stuff){
   $amount = count($stuff);
   $last_key = $amount - 1;

   foreach ($stuff as $key => $val) {

       // Do stuff

       if ($key == $last_key) {
           // Reset array cursor so we can loop through it again...
           return false;
       }

   }
}

while(stuff($stuff)===FALSE){
    //say hello
}
于 2013-10-18T17:01:39.517 回答