【问题标题】:How can I find the max attribute in an array of objects?如何在对象数组中找到 max 属性?
【发布时间】:2023-03-24 06:22:01
【问题描述】:

如何找到数组中对象的最大值?

假设我有一个这样的对象数组:

$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 遍历数组,但有没有更优雅的方法使用内置函数?

【问题讨论】:

    标签: php arrays object


    【解决方案1】:

    所有示例都假定$prop 是对象属性的名称,例如您的示例中的value

    function max_attribute_in_array($array, $prop) {
        return max(array_map(function($o) use($prop) {
                                return $o->$prop;
                             },
                             $array));
    }
    
    • array_map 获取每个数组元素并将对象的属性返回到一个新数组中
    • 然后在该数组上返回 max 的结果

    为了好玩,这里你可以传入maxmin 或任何对数组进行操作的第三个参数:

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

    这是来自 cmets 的 Mark Bakerarray_reduce

    $result = array_reduce(function($carry, $o) use($prop) {
                               $carry = max($carry, $o->$prop);
                               return $carry;
                           }, $array, -PHP_INT_MAX);
    

    【讨论】:

    • 通过我的单元测试运行它,就像做梦一样,谢谢
    • 了解 PHP 7 的奖励积分,可惜我选择在这个项目中使用 5.6
    • 类似:array_reduce( function($carry, $o) { $carry = max($carry, $o->$prop); return $carry; } $array, -PHP_INT_MAX );
    【解决方案2】:

    试试这个:

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

    回复:

    float 1.2
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-08-16
      • 1970-01-01
      • 2018-05-07
      • 2022-08-24
      • 1970-01-01
      • 2017-08-08
      • 1970-01-01
      相关资源
      最近更新 更多