我目前能够使用自定义排序方法对多维数组进行排序。每个数组 lineupSet
都有 n
个项目。函数 sort_points
将每个 lineupSet
从最高到最低 totalPoints
排序,然后它会给我 lineupSet
与最高的总 totalPoints
。我目前正在改变方法,我仍然想首先对每个 lineupSet
进行排序,然后从高到低排序。然后我想根据给定的计数获得每个 lineupSet
的最高 totalPoints
。解决这个问题的最佳方法是什么?
测试数组:
$testArray = [[
"lineupSet" => [
[[
"formula" => [
"totalPoints" => 214.61,
],
"name" => "arr0-test0",
], [
"formula" => [
"totalPoints" => 201.17,
],
"name" => "arr0-test1",
]], [
"formula" => [
"totalPoints" => 5.01,
],
"name" => "arr0-test2",
]],
], [
"lineupSet" => [
[[
"formula" => [
"totalPoints" => 214.76,
],
"name" => "arr1-test0",
], [
"formula" => [
"totalPoints" => 220.66,
],
"name" => "arr1-test1",
]],
],
], [
"lineupSet" => [
[[
"formula" => [
"totalPoints" => 205.71,
],
"name" => "arr2-test0",
], [
"formula" => [
"totalPoints" => 204.43,
],
"name" => "arr2-test1",
]],
],
], [
"lineupSet" => [
[[
"formula" => [
"totalPoints" => 205.48,
],
"name" => "arr3-test0",
], [
"formula" => [
"totalPoints" => 203.51,
],
"name" => "arr3-test1",
]],
],
]];
排序函数
function sum_points($v) {
$totalPoints = 0;
foreach ($v['lineupSet'] as $lset) {
if (isset($lset['formula'])) {
$totalPoints += $lset['formula']['totalPoints'];
}
else {
foreach ($lset as $l) {
$totalPoints += $l['formula']['totalPoints'];
}
}
}
return $totalPoints;
}
function sort_points($a, $b) {
return sum_points($b) - sum_points($a);
}
usort($testArray, 'sort_points');
print_r($testArray[0]);
例如,我想获得前两名最高的“totalPoints”。期望的结果:
Array (
[lineupSet] => Array
(
[0] => Array
(
[0] => Array
(
[formula] => Array
(
[totalPoints] => 220.66
)
[name] => arr1-test1
)
[1] => Array
(
[formula] => Array
(
[totalPoints] => 214.76
)
[name] => arr0-test0
)
)
)
)
我想对前 n
最高 totalPoints
做同样的事情。请记住,它有时必须从每个 lineupSet
中获取最高 totalPoints
的 n
项。
最佳答案
我认为最好使用一个对象,然后在对数据进行排序时可以保留最大值(也可以使用构造函数对数组进行排序)。
Class SortHelper{
public $max = 0;
private function checkMax($totalPoints){
if($totalPoints > $this->max)
$this->max = $totalPoints;
}
private function sum_points($v) {
$totalPoints = 0;
foreach ($v['lineupSet'] as $lset) {
if (isset($lset['formula'])) {
$totalPoints += $lset['formula']['totalPoints'];
$this->checkMax($lset['formula']['totalPoints']);
}
else {
foreach ($lset as $l) {
$totalPoints += $l['formula']['totalPoints'];
$this->checkMax($l['formula']['totalPoints']);
}
}
}
return $totalPoints;
}
private function sort_points($a, $b) {
return $this->sum_points($b) - $this->sum_points($a);
}
public function sort($array){
usort( $array, [$this, 'sort_points']);
return $array;
}
}
那么你会:
$sortHelper = new SortHelper();
$sorted_array = $sortHelper->sort($testArray);
var_dump($sorted_array[0]);
var_dump($sortHelper->max);
关于php - 按最高值对 n 个项目进行多维自定义排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55720393/