PHP 查找对象在数组中具有最高值

标签 php arrays sorting

我正在寻找找到包含最高 sort 值的对象的最短方法。

array(5) {
  [0]=>
  object(stdClass)#212 (3) {
    ["id"]=>
    int(1)
    ["display_name"]=>
    string(8) "Activate"
    ["sort"]=>
    int(1)
  }
  [1]=>
  object(stdClass)#213 (3) {
    ["id"]=>
    int(2)
    ["display_name"]=>
    string(7) "Cutting"
    ["sort"]=>
    int(2)
  }
  [2]=>
  object(stdClass)#214 (3) {
    ["id"]=>
    int(3)
    ["display_name"]=>
    string(6) "Sewing"
    ["sort"]=>
    int(3)
  }
  [3]=>
  object(stdClass)#215 (3) {
    ["id"]=>
    int(4)
    ["display_name"]=>
    string(9) "Finishing"
    ["sort"]=>
    int(4)
  }
  [4]=>
  object(stdClass)#216 (3) {
    ["id"]=>
    int(5)
    ["display_name"]=>
    string(10) "Deactivate"
    ["sort"]=>
    int(5)
  }
}

下面是我的练习,但我认为它很复杂并且代码很长。

// $gateways is the array contains a list of objects.

// find max sort value in array first
$max = max( array_map(function( $row ){ return $row->sort; }, $gateways) );

// then find in array object with sort value is equal to $max value
$filter = array_filter($gateways, function($row) use ($max){ 
  return $max == $row->sort;
});

if(count($filter)){
  $finalResult = array_shift($filter);
}

有没有像 Javascript 中的 reduce 这样更短的方法?

谢谢。

最佳答案

我终于做到了。

$result = array_reduce($gateways, function($a, $b){
  return $a ? ($a->sort > $b->sort ? $a : $b) : $b;
});

关于PHP 查找对象在数组中具有最高值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43339860/

相关文章:

php - 检查产品的可用性

php - Controller 和路由器的区别?

python - 嵌套循环二维数组的计算与构造

javascript - 如何在javascript中获取对象数组中的值

php - 有条件的 CakePHP 可包含行为

linux - 当数字相等时按数字而不是字母顺序排序

php - 在 laravel v5.3 中显示表格

php - 新文件的 Ubuntu 编码

python - 元素的列表比较

wpf - 如何按照与 Multibound 字段相同的顺序对 DataGridTemplateColumn(使用 MultiBinding)进行排序