1
我正在尋找最短的方法來查找包含最高值sort
的對象。PHP查找對象在數組中的值最高
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
?
謝謝。
http://php.net/manual/en/function.array-reduce.php – splash58