问题
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