php 在 foreach 循环中取消设置数组值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2008866/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:39:39  来源:igfitidea点击:

Unsetting array values in a foreach loop

phparraysforeachunset

提问by Matt

I have a foreach loop set up to go through my array, check for a certain link, and if it finds it removes that link from the array.

我设置了一个 foreach 循环来遍历我的数组,检查某个链接,如果发现它从数组中删除该链接。

My code:

我的代码:

foreach($images as $image)
{
    if($image == 'http://i27.tinypic.com/29yk345.gif' ||
    $image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
    $image == 'http://i42.tinypic.com/9pp2456x.gif')
    {
        unset($images[$image]);
    }
}

But it doesn't remove the array entires. It's probably something to do with $images[$image], as that's not the key of the array entry, only the content? Is there a way to do this without incorporating a counter?

但它不会删除整个数组。这可能与 有关$images[$image],因为那不是数组条目的键,只有内容?有没有办法在不合并计数器的情况下做到这一点?

Thanks.

谢谢。

EDIT:Thanks guys, but now I have another problem where the array entries don't actually get deleted.

编辑:谢谢大家,但现在我有另一个问题,数组条目实际上没有被删除。

My new code:

我的新代码:

foreach($images[1] as $key => $image)
{
    if($image == 'http://i27.tinypic.com/29yk345.gif')
    $image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
    $image == 'http://i42.tinypic.com/9pp2456x.gif')
    {
        unset($images[$key]);
    }
}

$images is actuallty a two-dimensional array now hence why I need $images[1]. I have checked and it successfully goes around the array elements, and some elements do actually have some of those URLs in that I wish to delete, but they're not getting deleted. This is my $imagesarray:

$images 现在实际上是一个二维数组,因此我需要 $images[1]。我已经检查过,它成功地绕过了数组元素,有些元素确实有一些我希望删除的 URL,但它们并没有被删除。这是我的$images数组:

Array
(
    [0] => Array
        (
            [0] => useless
            [1] => useless
            [2] => useless
            [3] => useless
            [4] => useless
        )

    [1] => Array
        (
            [0] => http://i27.tinypic.com/29yk345.gif
            [1] => http://img3.abload.de/img/10nx2340fhco.gif
            [2] => http://img3.abload.de/img/10nx2340fhco.gif
            [3] => http://i42.tinypic.com/9pp2456x.gif
        )

)

Thanks!

谢谢!

回答by hsz

foreach($images as $key => $image)
{
    if(in_array($image, array(
       'http://i27.tinypic.com/29ykt1f.gif',
       'http://img3.abload.de/img/10nxjl0fhco.gif',
       'http://i42.tinypic.com/9pp2tx.gif',
    ))
    {
        unset($images[$key]);
    }
}

回答by selfawaresoup

Try that:

试试看:

foreach ($images[1] as $key => &$image) {
    if (yourConditionGoesHere) {
        unset($images[1][$key])
    }
}
unset($image); // detach reference after loop  

Normally, foreachoperates on a copy of your array so any changes you make, are made to that copy and don't affect the actual array.

通常,foreach对数组的副本进行操作,因此您所做的任何更改都会对该副本进行,并且不会影响实际的数组。

So you need to unset the values via $images[$key];

因此,您需要通过$images[$key];取消设置值。

The reference on &$imageprevents the loop from creating a copy of the array which would waste memory.

on 的引用&$image可防止循环创建会浪费内存的数组副本。

回答by Tomas M

To answer the initial question (after your edit), you need to unset($images[1][$key]);

要回答最初的问题(编辑后),您需要 unset($images[1][$key]);

Now some more infos how PHP works: You can safely unset elements of the array in foreach loop, and it doesn't matter if you have & or not for the array item. See this code:

现在有更多关于 PHP 如何工作的信息:您可以在 foreach 循环中安全地取消设置数组的元素,并且对于数组项是否有 & 并不重要。看到这个代码:

$a=[1,2,3,4,5];
foreach($a as $key=>$val)
{
   if ($key==3) unset($a[$key]);
}
print_r($a);

This prints:

这打印:

Array
(
    [0] => 1
    [1] => 2
    [2] => 3
    [4] => 5
)

So as you can see, if you unset correct thing within the foreach loop, everything works fine.

如您所见,如果您在 foreach 循环中取消设置正确的内容,则一切正常。

回答by webmaster

You can use the index of the array element to remove it from the array, the next time you use the $listvariable, you will see that the array is changed.

您可以使用数组元素的索引将其从数组中移除,下次使用该$list变量时,您将看到数组已更改。

Try something like this

尝试这样的事情

foreach($list as $itemIndex => &$item) {

   if($item['status'] === false) {
      unset($list[itemIndex]);
   }

}

回答by Gumbo

$imageis in your case the value of the item and not the key. Use the following syntax to get the key too:

$image在你的情况下是项目的价值而不是关键。也可以使用以下语法来获取密钥:

foreach ($images as $key => $value) {
    /* … */
}

Now you can delete the item with unset($images[$key]).

现在您可以使用 删除该项目unset($images[$key])

回答by murph.vienna

You would also need a

你还需要一个

$i--;

after each unset to not skip an element/

在每次取消设置后不跳过一个元素/

Because when you unset $item[45], the next element in the for-loop should be $item[45]- which was [46]before unsetting. If you would not do this, you'd always skip an element after unsetting.

因为当你 unset 时$item[45],for 循环中的下一个元素应该是$item[45]- 这是[46]在 unsetting 之前。如果你不这样做,你总是会在取消设置后跳过一个元素。

回答by Peter Porfy


foreach($images as $key=>$image)                                
{               
   if($image == 'http://i27.tinypic.com/29ykt1f.gif' ||    
   $image == 'http://img3.abload.de/img/10nxjl0fhco.gif' ||    
   $image == 'http://i42.tinypic.com/9pp2tx.gif')     
   { unset($images[$key]); }                               
}

!!foreach($images as $key=>$image

!!foreach($images as $key=>$image

cause $image is the value, so $images[$image] make no sense.

因为 $image 是值,所以 $images[$image] 没有意义。

回答by Pascal MARTIN

One solution would be to use the key of your items to remove them -- you can both the keys and the values, when looping using foreach.

一种解决方案是使用您的项目的键来删除它们——当使用foreach循环时,您可以同时使用键和值。

For instance :

例如 :

$arr = array(
    'a' => 123,
    'b' => 456,
    'c' => 789, 
);

foreach ($arr as $key => $item) {
    if ($item == 456) {
        unset($arr[$key]);
    }
}

var_dump($arr);

Will give you this array, in the end :

最后会给你这个数组:

array
  'a' => int 123
  'c' => int 789


Which means that, in your case, something like this should do the trick :


这意味着,在您的情况下,这样的事情应该可以解决问题:

foreach($images as $key => $image)
{
    if($image == 'http://i27.tinypic.com/29yk345.gif' ||
    $image == 'http://img3.abload.de/img/10nx2340fhco.gif' ||
    $image == 'http://i42.tinypic.com/9pp2456x.gif')
    {
        unset($images[$key]);
    }
}

回答by jameslimousin

Sorry for the late response, I recently had the same problem with PHP and found out that when working with arrays that do not use $key => $valuestructure, when using the foreachloop you actual copy the value of the position on the loop variable, in this case $image. Try using this code and it will fix your problem.

抱歉回复晚了,我最近在使用 PHP 时遇到了同样的问题,并发现在处理不使用$key => $value结构的数组时,在使用foreach循环时,您实际复制了循环变量上的位置值,在这种情况下为$image. 尝试使用此代码,它将解决您的问题。

for ($i=0; $i < count($images[1]); $i++)
{

    if($images[1][$i] == 'http://i27.tinypic.com/29yk345.gif' ||

    $images[1][$i] == 'http://img3.abload.de/img/10nx2340fhco.gif' ||

    $images[1][$i] == 'http://i42.tinypic.com/9pp2456x.gif')

    {

        unset($images[1][$i]);

    }

}

var_dump($images);die();