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

前端 未结 2 961
日久生厌
日久生厌 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 08:04

    try this:

    $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';
    
    $data_points = [$point1, $point2, $point3];
    
    function max_attribute_in_array($data_points, $value='value'){
        $max=0;
        foreach($data_points as $point){
            if($max < (float)$point->{$value}){
                $max = $point->{$value};
            }
        }
        return $max;
    }
    $max = max_attribute_in_array($data_points);
    var_dump($max);
    

    response:

    float 1.2
    

提交回复
热议问题