How to search in array of std object (array of object) using in_array php function? [duplicate]

孤者浪人 提交于 2019-12-11 19:55:59

问题


I have following std Object array

Array
(
    [0] => stdClass Object
        (
            [id] => 545
        )

    [1] => stdClass Object
        (
            [id] => 548
        )

    [2] => stdClass Object
        (
            [id] => 550
        )

    [3] => stdClass Object
        (
            [id] => 552
        )

    [4] => stdClass Object
        (
            [id] => 554
        )

)

I want to search for value of [id] key using loop. I have following condition to check whether value is exist or not like below

$flag = 1;
if(!in_array($value->id, ???)) {
    $flag = 0;
}

Where ??? I want to search in array of std Object's [id] key.

Can any one help me for this?


回答1:


If the array isn't too big or the test needs to be performed multiple times, you can map the properties in your array:

$ids = array_map(function($item) {
    return $item->id;
}, $array);

And then:

if (!in_array($value->id, $ids)) { ... }



回答2:


try:

foreach ($array as $val) {
 if (!in_array($id, (array) $val)) {
 ...
 }
}



回答3:


Why not just cast the objects as arrays:

foreach ($array as $a) {
     if (!in_array($id, (array) $a)) {
     ...
     }
}



回答4:


Assuming your array is names $yourArray ,

$newArr = array();
foreach ($yourArray as $key=>$value) {
    $newArr[] = $value->id;
}

And now $newArr is like : array(545,548,550,552,554)

AND you can search in it by :

$valueOfSearch = ... ;
$flag = 1;
if(!in_array($valueOfSearch,$newArr)) {
    $flag = 0;
}


来源:https://stackoverflow.com/questions/21275014/how-to-search-in-array-of-std-object-array-of-object-using-in-array-php-functi

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