在 foreach 循环中取消设置数组值 [英] Unsetting array values in a foreach loop

查看:45
本文介绍了在 foreach 循环中取消设置数组值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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($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]);
    }
}

但它不会删除整个数组.这可能与$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?

谢谢.

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

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

我的新代码:

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

$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 $images array:

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
        )

)

谢谢!

推荐答案

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]);
    }
}

这篇关于在 foreach 循环中取消设置数组值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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