如何在循环遍历数组时将项目添加到数组?

2021-12-26 00:00:00 arrays loops foreach php

foreach 循环中,PHP 似乎在开始时读取整个数组,因此如果您突然需要将新项目附加到数组中,它们将不会被循环处理:

On a foreach loop, it seems PHP reads the whole array at the beginning, so if you suddenly need to append new items to the array they won't get processed by the loop:

$a = array (1,2,3,4,5,6,7,8,9,10);

foreach ($a as $b)
    {
        echo " $b ";
        if ($b ==5) $a[] = 11;
    }

只打印出:1 2 3 4 5 6 7 8 9 10

推荐答案

只需创建一个你正在循环的数组的引用副本

Just create a reference copy of the array you are looping

$a = array(1,2,3,4,5,6,7,8,9,10);
$t = &$a; //Copy
foreach ( $t as $b ) {
    echo " $b ";
    if ($b == 5)
        $t[] = 11;
}

或者直接使用ArrayIterator

$a = new ArrayIterator(array(1,2,3,4,5,6,7,8,9,10));
foreach ( $a as $b ) {
    echo "$b ";
    if ($b == 5)
        $a->append(11);
}

输出

 1 2 3 4 5 6 7 8 9 10 11

观看现场演示

相关文章