如何找到数组中对象的最大值?
假设我有一个这样的对象数组:
$data_points = [$point1, $point2, $point3];
在哪里
$point1 = new stdClass;
$point1->value = 0.2;
$point1->name = 'Bob';
$point2 = new stdClass;
$point2->value = 1.2;
$point2->name = 'Dave';
$point3 = new stdClass;
$point3->value = 0.8;
$point3->name = 'Steve';
我想做这样的事情:
$max = max_attribute_in_array($data_points, 'value');
我知道我可以使用 foreach
遍历数组,但是是否有使用内置函数的更优雅的方法?
最佳答案
所有示例都假定 $prop
是对象属性的名称,例如您示例中的 value
:
function max_attribute_in_array($array, $prop) {
return max(array_map(function($o) use($prop) {
return $o->$prop;
},
$array));
}
array_map
获取每个数组元素并将对象的属性返回到一个新数组中- 然后只返回该数组上
max
的结果
为了好玩,这里你可以传入 max
或 min
或任何对数组操作的东西作为第三个参数:
function calc_attribute_in_array($array, $prop, $func) {
$result = array_map(function($o) use($prop) {
return $o->$prop;
},
$array);
if(function_exists($func)) {
return $func($result);
}
return false;
}
$max = calc_attribute_in_array($data_points, 'value', 'max');
$min = calc_attribute_in_array($data_points, 'value', 'min');
如果使用 PHP >= 7,则 array_column
适用于对象:
function max_attribute_in_array($array, $prop) {
return max(array_column($array, $prop));
}
这里是 Mark Baker来自评论的 array_reduce
:
$result = array_reduce(function($carry, $o) use($prop) {
$carry = max($carry, $o->$prop);
return $carry;
}, $array, -PHP_INT_MAX);
关于php - 如何在对象数组中找到 max 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36602362/