如何从foreach循环内部数组中删除对象吗? [英] How to delete object from array inside foreach loop?

查看:916
本文介绍了如何从foreach循环内部数组中删除对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过对象的数组迭代,你想删除此基础上的id属性的对象之一,但我的code不起作用。

 的foreach($数组作为$元素){
    的foreach($元素作为$关键=> $值){
        如果($键=='ID'和;&安培; $价值=='searched_value'){
            //从$数组中删除此特定对象
            未设置($元); //这不起作用
            未设置($数组,$元); //没有做到这一点
        }
    }
}

任何建议。谢谢你。


解决方案

 的foreach($数组作为$ elementKey => $元素){
    的foreach($元素作为$ valueKey => $值){
        如果($ valueKey =='ID'和;&安培; $价值=='searched_value'){
            //从$数组中删除此特定对象
            未设置($数组[$ elementKey]);
        }
    }
}

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.

解决方案

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

这篇关于如何从foreach循环内部数组中删除对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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