问题描述
我想要一个foreach循环,其中初始数组在循环内更改.
i want to have a foreach loop where the initial array is changed inside the loop.
例如
$array = array('red', 'blue');
foreach($array as $key => $value) {
$array[] = 'white';
echo $value . '<br />';
}
在此循环中,尽管我在循环中添加了另一个元素,该循环仍将打印出红色和蓝色.
in this loop the loop will print out red and blue although i add another element inside the loop.
是否有任何方法可以在循环内更改初始数组,因此将添加新元素,并且无论更改如何,foreach都将使用新数组?
is there any way to change the initial array inside the loop so new elements will be added and the foreach will use the new array whatever is changed?
我需要针对特定任务的这种逻辑:
i need this kind of logic for a specific task:
我将有一个if语句来搜索链接.如果该链接存在,则将其添加到阵列.链接内容是否包含另一个链接将被提取以进行检查.如果是这样,则添加此链接,然后将获取内容,依此类推...如果未进一步建立链接,则foreach循环将退出
i will have a if statement that search for a link. if that link exists, it is added to the array. the link content will be fetched to be examined if it contains another link. if so, this link is added, and the content will be fetched, so on so forth.. when no link is further founded, the foreach loop will exit
推荐答案
我认为使用foreach
循环是不可能的,至少在您编写它的方式上:这似乎不只是foreach
作品;引用 foreach
的手册页:
I don't think this is possible with a foreach
loop, at least the way you wrote it : doesn't seem to just be the way foreach
works ; quoting the manual page of foreach
:
在仔细考虑了该注释之后,实际上是有可能的,这就是解决方法:
注释说:"除非引用了数组";这意味着这部分代码应该可以工作:
The note says "Unless the array is referenced" ; which means this portion of code should work :
$i = 0;
$array = array('red', 'blue');
foreach($array as $key => & $value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
}
在$value
之前注意&
.
Note the &
before $value
.
它实际上显示为:
red
blue
white
white
white
white
这意味着添加&
实际上是您想要的解决方案,可以从foreach
循环内部修改数组;-)
Which means adding that &
is actually the solution you were looking for, to modify the array from inside the foreach
loop ;-)
这是我在考虑该注释之前提出的解决方案:
您可以使用while
循环执行此操作,手动"完成更多工作;例如:
You could do that using a while
loop, doing a bit more work "by hand" ; for instance :
$i = 0;
$array = array('red', 'blue');
$value = reset($array);
while ($value) {
$array[] = 'white';
echo $value . '<br />';
if ($i++ >= 5) {
break; // security measure to ensure non-endless loop
}
$value = next($array);
}
将为您提供此输出:
red
blue
white
white
white
white
这篇关于更改foreach循环内的初始数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!