如何在对象数组中找到max属性? [英] How can I find the max attribute in an array of objects?
问题描述
如何找到数组中对象的最大值?
说我有一个这样的对象数组:
Say I have an array of objects like this:
$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
遍历数组,但是使用内置函数有没有更优雅的方法?
I know I can iterate over the array with a foreach
but is there a more elegant method using built-in functions?
推荐答案
在所有示例中,假设 $ prop
是对象属性的名称,例如您的示例中的 value
:
All examples assume that $prop
is the name of an object property like value
in your example:
function max_attribute_in_array($array, $prop) {
return max(array_map(function($o) use($prop) {
return $o->$prop;
},
$array));
}
-
array_map
接受每个数组元素,并将对象的属性返回到新数组中 - 然后只返回该数组上
max
的结果 array_map
takes each array element and returns the property of the object into a new array- Then just return the result of
max
on that array
为了娱乐,您可以在此处传递 max
或 min
或将对数组进行操作的任何内容作为第三个参数:
For fun, here you can pass in max
or min
or whatever operates on an array as the third parameter:
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
可在对象上运行:
If using PHP >= 7 then array_column
works on objects:
function max_attribute_in_array($array, $prop) {
return max(array_column($array, $prop));
}
这里是马克·贝克(Mark Baker)的 array_reduce
(来自评论):
Here is Mark Baker's array_reduce
from the comments:
$result = array_reduce(function($carry, $o) use($prop) {
$carry = max($carry, $o->$prop);
return $carry;
}, $array, -PHP_INT_MAX);
这篇关于如何在对象数组中找到max属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!