我怎样才能改变我的数组,直接影响我的foreach循环? [英] How can I change my array, which directly affects my foreach loop?

查看:115
本文介绍了我怎样才能改变我的数组,直接影响我的foreach循环?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用foreach循环遍历一个数组。然而,在foreach循环中,我需要修改数组,以便它直接影响我的foreach循环。

所以我将举一个例子来解释我的问题:



pre $ <?php

$ array = [Red,Yellow,Blue,Orange ];
$ b foreach($ array as $ color){
if(($ key = array_search(Blue,$ array))!== false)
unset($ array [$键]);

echo $ color。 <峰; br> 中;

}

?>

输出:

红色
黄色
蓝色
橙色

所以你可以看到我 unset()值为 Blue 的数组元素。但我仍然在我的输出中。

现在我的问题是:如何取消设置值蓝色直接影响我的foreach循环,意味着我不会在输出中看到它,因为我在之前删除了我遍历该特定元素。

预期的输出是(注意:蓝色不在输出中):

  Red 
Yellow
Orange


解决方案

您可以通过引用另一个变量来分配数组,这样 is_ref 是1,意味着foreach循环不会遍历数组副本。



所以,只要把它放在你的foreach循环之前就可以了:

  $ arr =& $ array; 

有关更多信息,请参阅: PHP的foreach实际上是如何工作的?



另外请注意,因为有一些PHP 7中的更改: http://php.net/manual /en/migration70.incompatible.php#migration70.incompatible.foreach 这将不再适用于PHP 7。



如果你想要做同样的事情在PHP 7中的行为改变只是说,你要通过引用循环访问数组,例如

  foreach($ array as& $ color)


I loop through an array, which I have, using a foreach loop. However within the foreach loop I need to modify the array, so that it directly affects my foreach loop.

So I will make an example of my problem:

<?php

    $array = ["Red", "Yellow", "Blue", "Orange"];

    foreach($array as $color) {
        if(($key = array_search("Blue", $array)) !== false) 
            unset($array[$key]);

        echo $color . "<br>";

    }

?>

output:

Red
Yellow
Blue
Orange

So as you can see I unset() the array element with the value Blue. But I still have it in my output.

Now my question is: How can I unset the element with the value Blue, so that it directly affects my foreach loop, means I won't see it anymore in the output, since I deleted it before I loop over that specific element.

Expected output would be (Note: Blue is not in the output):

Red
Yellow
Orange

解决方案

You could assign your array by reference to another variable, so that is_ref is 1, means the foreach loop doesn't loop over a copy of your array anymore.

So just put this before your foreach loop:

$arr = &$array;

For more information how foreach actually works see: How does PHP 'foreach' actually work?

Also note, since there are some changes in PHP 7: http://php.net/manual/en/migration70.incompatible.php#migration70.incompatible.foreach this won't work anymore in PHP 7.

If you want to do the same in PHP 7 where the behavior is changed just say that you want to loop through the array by reference, e.g.

foreach($array as &$color)

这篇关于我怎样才能改变我的数组,直接影响我的foreach循环?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆