如何在 foreach 循环内从数组中删除对象?
我遍历一个对象数组,并想根据其中一个对象的“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
}
}
}
任何建议。谢谢。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
请注意主要答案。
with
函数
并调用它返回的
而不是
这是因为 unset 不会重新索引数组。
它重新索引。 (如果我们需要的话)
Be careful with the main answer.
with
and calling the function
it returns
instead of
It is because unset does not re-index the array.
It reindexes. (if we need it)
您的 unset 语法似乎无效,并且缺乏重新索引可能会在将来造成麻烦。请参阅:有关 PHP 数组的部分 。
正确的语法如上所示。另请记住 数组值 用于重新索引,这样您就不会为之前删除的内容建立索引。
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.
这应该可以解决问题......
This should do the trick.....
您还可以使用
foreach
值的引用:You can also use references on
foreach
values:我不是一个很好的 php 程序员,但我可以说,在 C# 中,您无法在迭代数组时修改数组。您可能想尝试使用 foreach 循环来识别元素的索引或要删除的元素,然后在循环后删除元素。
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.