How to delete object from array inside foreach loop?

六月ゝ 毕业季﹏ 提交于 2019-11-26 10:15:09

问题


I iterate through an array of objects and want to delete one of the objects based on it\'s \'id\' property, but my code doesn\'t work.

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
        } 
    }
}

Any suggestions. Thanks.


回答1:


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



回答2:


You can also use references on foreach values:

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



回答3:


It looks like your syntax for unset is invalid, and the lack of reindexing might cause trouble in the future. See: the section on PHP arrays.

The correct syntax is shown above. Also keep in mind array-values for reindexing, so you don't ever index something you previously deleted.




回答4:


This should do the trick.....

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



回答5:


I'm not much of a php programmer, but I can say that in C# you cannot modify an array while iterating through it. You may want to try using your foreach loop to identify the index of the element, or elements to remove, then delete the elements after the loop.



来源:https://stackoverflow.com/questions/2304570/how-to-delete-object-from-array-inside-foreach-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!