且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何找到在PHP中数组对象的索引?

更新时间:2023-10-26 12:14:10

  $发现= 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.