如何从foreach循环中的数组中删除对象?

时间:2010-02-21 02:51:30

标签: php foreach unset arrays

我遍历一个对象数组,并希望根据它的'id'属性删除其中一个对象,但我的代码不起作用。

foreach($array as $element) {
    foreach($element as $key => $value) {
        if($key == 'id' && $value == 'searched_value'){
            //delete this particular object from the $array
            unset($element);//this doesn't work
            unset($array,$element);//neither does this
        } 
    }
}

任何建议。感谢。

6 个答案:

答案 0 :(得分:205)

foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        if($valueKey == 'id' && $value == 'searched_value'){
            //delete this particular object from the $array
            unset($array[$elementKey]);
        } 
    }
}

答案 1 :(得分:2)

您还可以使用foreach值的引用:

foreach($array as $elementKey => &$element) {
    // $element is the same than &$array[$elementKey]
    if (isset($element['id']) and $element['id'] == 'searched_value') {
        unset($element);
    }
}

答案 2 :(得分:1)

看起来你的unset语法是无效的,缺乏重新索引可能会在将来引起麻烦。见:the section on PHP arrays

上面显示了正确的语法。另请注意array-values以便重新编制索引,因此您不会将之前删除的内容编入索引。

答案 3 :(得分:1)

这应该可以解决问题.....

reset($array);
while (list($elementKey, $element) = each($array)) {
    while (list($key, $value2) = each($element)) {
        if($key == 'id' && $value == 'searched_value') {
            unset($array[$elementKey]);
        }
    }
}

答案 4 :(得分:1)

注意主要答案。

使用

[['id'=>1,'cat'=>'vip']
,['id'=>2,'cat'=>'vip']
,['id'=>3,'cat'=>'normal']

并调用函数

foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        if($valueKey == 'cat' && $value == 'vip'){
            //delete this particular object from the $array
            unset($array[$elementKey]);
        } 
    }
}

它返回

[2=>['id'=>3,'cat'=>'normal']

代替

[0=>['id'=>3,'cat'=>'normal']

这是因为未设置不会重新索引数组。

它重新编制索引。 (如果需要的话)

$result=[];
foreach($array as $elementKey => $element) {
    foreach($element as $valueKey => $value) {
        $found=false;
        if($valueKey === 'cat' && $value === 'vip'){
            $found=true;
            $break;
        } 
        if(!$found) {
           $result[]=$element;
        }
    }
}

答案 5 :(得分:0)

我不是一个php程序员,但我可以说在C#中你不能在迭代它时修改数组。您可能想尝试使用foreach循环来标识元素的索引或要删除的元素,然后在循环后删除元素。