数组看起来像:
[0] => stdClass Object
(
[ID] => 420
[name] => Mary
)
[1] => stdClass Object
(
[ID] => 10957
[name] => Blah
)
...
我有一个整数变量$v。
我如何选择一个数组条目,其中有一个对象的ID属性有$v值?
我有时喜欢使用array_reduce()函数来执行搜索。它类似于array_filter(),但不会影响所搜索的数组,允许您对同一对象数组执行多次搜索。
$haystack = array($obj1, $obj2, ...); //some array of objects
$needle = 'looking for me?'; //the value of the object's property we want to find
//carry out the search
$search_results_array = array_reduce(
$haystack,
function($result_array, $current_item) use ($needle){
//Found the an object that meets criteria? Add it to the the result array
if ($current_item->someProperty == $needle){
$result_array[] = $current_item;
}
return $result_array;
},
array() //initially the array is empty (i.e.: item not found)
);
//report whether objects found
if (count($search_results_array) > 0){
echo "found object(s): ";
print_r($search_results_array[0]); //sample object found
} else {
echo "did not find object(s): ";
}