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

StackOverflow https://stackoverflow.com/questions/21275014

  •  01-10-2022
  •  | 
  •  

質問

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?

役に立ちましたか?

解決

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)) { ... }

他のヒント

try:

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

Why not just cast the objects as arrays:

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

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;
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top