连续循环遍历数组

时间:2013-10-18 16:52:54

标签: php arrays loops foreach

我正在尝试研究如何连续循环遍历数组,但显然使用foreach不起作用,因为它适用于数组的副本或类似的行。

我试过了:

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

}

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

6 个答案:

答案 0 :(得分:4)

您可以使用while循环完成此操作:

while (list($key, $value) = each($stuff)) {
    // code
    if ($key == $last_key) {
        reset($stuff); 
    }
}

答案 1 :(得分:3)

这个循环永远不会停止:

while(true) {
    // do something
}

如果有必要,你可以像这样打破循环:

while(true) {
    // do something
    if($arbitraryBreakCondition === true) {
        break;
    }
}

答案 2 :(得分:2)

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

$infinite = new InfiniteIterator(new ArrayIterator($array));
foreach ($infinite as $key => $val) {
    // ...
}

答案 3 :(得分:2)

这里是使用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

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

答案 4 :(得分: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;
    }


}

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

答案 5 :(得分: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
}
相关问题