简体   繁体   English

连续遍历数组

[英]Continuously looping through an array

I'm trying to work out how to continuously loop through an array, but apparently using foreach doesn't work as it works on a copy of the array or something along those lines. 我正在尝试找出如何连续遍历数组的方法,但是显然,使用foreach不能正常工作,因为它可以处理数组的副本或沿这些方向的东西。

I tried: 我试过了:

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

}

But obviously that didn't work. 但是显然那是行不通的。 What are my choices here? 我在这里有什么选择?

You can accomplish this with a while loop: 您可以使用while循环完成此操作:

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

This loop will never stop: 此循环永远不会停止:

while(true) {
    // do something
}

If necessary, you can break your loop like this: 如有必要,您可以像这样中断循环:

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

An easy way is to combine an ArrayIterator with an InfiniteIterator . 一种简单的方法是将ArrayIteratorInfiniteIterator组合在一起。

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

You could use a for loop and just set a condition that's always going to be true - for example: 您可以使用for循环并仅设置始终为true的条件-例如:

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


}

Obviously, as other's have pointed out - make sure you've got something to stop the looping before you run that! 显然,正如其他人指出的那样,请确保在运行循环之前确保有一些东西可以停止循环!

Here's one using reset() and next(): 这是使用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";
};

Output: 输出:

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

I was rather surprised to find no such native function. 我很惊讶地发现没有这样的本机功能。 This is a building block for a Cartesian product. 这是笛卡尔积的构造块。

Using a function and return false in a while loop: 使用一个函数并在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
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM