如何找到在PHP中数组对象的索引? [英] How to find index of object in php array?
本文介绍了如何找到在PHP中数组对象的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
下面是我的数组的print_r的输出:
阵列
(
[0] => stdClass的对象
(
[的itemId] => 560639000019
[名] =>项目NO1
[code => 00001
[数量] =>五
[ID] => 2
)[1] => stdClass的对象
(
[的itemId] => 470639763471
[名] =>第二项
[code => 76347
[数量] => 9
[ID] => 4
)[2] => stdClass的对象
(
[的itemId] => 56939399632
[名] =>项目第3期
[code => 39963
[数量] => 6
[ID] => 7
))
我如何能找到对象的索引与[ID] => 4,以便从数组中删除呢?
解决方案
$发现= FALSE;
的foreach($值$关键=> $值){
如果($值 - > ID == 4){
$找到= TRUE;
打破;
}
}如果($找到)未设置($值[$关键]);
这被认为是快于任何其他的解决方案,因为我们只遍历阵列
来,直到我们找到了对象,我们要删除。
注意:,而迭代,所以我们做的事后这里,您不应该删除数组的元素。
Here is print_r output of my array:
Array
(
[0] => stdClass Object
(
[itemId] => 560639000019
[name] => Item no1
[code] => 00001
[qty] => 5
[id] => 2
)
[1] => stdClass Object
(
[itemId] => 470639763471
[name] => Second item
[code] => 76347
[qty] => 9
[id] => 4
)
[2] => stdClass Object
(
[itemId] => 56939399632
[name] => Item no 3
[code] => 39963
[qty] => 6
[id] => 7
)
)
How can I find index of object with [id] => 4 in order to remove it from array?
解决方案
$found = false;
foreach($values as $key => $value) {
if ($value->id == 4) {
$found = true;
break;
}
}
if ($found) unset($values[$key]);
This is considered to be faster then any other solution since we only iterate the array
to until we find the object we want to remove.
Note: You should not remove an element of an array while iterating so we do it afterwards here.
这篇关于如何找到在PHP中数组对象的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文