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; //Copyforeach ( $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观看现场演示 这篇关于如何在循环遍历数组时将项目添加到数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 07-23 03:20