对PHP及其数组不熟悉我想知道是否有更好的方法可以进行这样的简单搜索:
$found = "0";
foreach ($myArray as $item) {
if ($item->id == "Foo") {
$found = $item->value;
break;
}
}
答案 0 :(得分:2)
另一种解决方案是使用array_filter
:
$matchingArray = array_filter($myArray, function($object) {
return $object->id == 'Foo';
});
它将迭代您的数组,并使用数组中的每个元素调用提供的callback
(第二个参数)。如果项目符合您的需要,回调需要返回true
,否则返回false
。
如果你只需要第一个:
if(count($matchingArray) > 0){
$firstMatch = $matchingArray[0];
}else{
// none found.
}
答案 1 :(得分:-2)
您可以使用
array_search()
或者你可以简单地使用:
if(in_array($foo, $bar)
其中$ foo是要查找的值,$ bar是数组