我有这个函数,它遍历对象数组以搜索匹配的键 => 值对。我很好奇是否没有更简单(或更优雅)的方式:
function count_class_attr($objects, $obj_key, $obj_val) {
$count = 0;
foreach ($objects as $object ) {
foreach ($object as $key => $value) {
if ($key == $obj_key && $value == $obj_val){
$count ++;
}
}
}
return $count;
}
我认为下面更接近我想要的。我正在循环一个对象数组,而不是一个数组数组——下面的函数会尽可能高效吗?
function count_class_attr($objects, $obj_key, $obj_val) {
$count = 0;
foreach ($objects as $object ) {
if (property_exists($object, $obj_key)) {
if($object->$obj_key == $obj_val) { $count ++; }
}
}
return $count;
}