How can I find the max attribute in an array of objects?

前端 未结 2 977
日久生厌
日久生厌 2021-01-04 07:19

How can I find the maximum value for the objects in my array?

Say I have an array of objects like this:

$data_points = [$point1, $po         


        
2条回答
  •  渐次进展
    2021-01-04 07:58

    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 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

    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');
    

    If using PHP >= 7 then array_column works on objects:

    function max_attribute_in_array($array, $prop) {
        return max(array_column($array, $prop));
    }
    

    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);
    

提交回复
热议问题