我目前正在尝试按其totalPoints
对多维数组进行排序。每个数组lineupSet
都有n
个项目。我正在尝试使lineupSet
总数最高。我怎样才能最有效地实现?以下是sudocode,因此无法正常工作。不确定如何处理。
代码
totalPoints
所需结果:
public function getHighestTotalPoints($testArray)
{
if (isset($testArray) && !empty($testArray)) {
uasort($testArray, function ($a, $b) {
return $a['lineupSet']['formula']['totalPoints'] <=> $b['lineupSet']['formula']['totalPoints'] ;
});
return array_reverse($testArray);
}
return null;
}
$testArray = [[
"lineupSet" => [
[[
"formula" => [
"totalPoints" => 214.61,
],
"name" => "test1",
], [
"formula" => [
"totalPoints" => 201.17,
],
"name" => "test2",
]], [
"formula" => [
"totalPoints" => 5.01,
],
"name" => "test3",
]],
], [
"lineupSet" => [
[[
"formula" => [
"totalPoints" => 220.66,
],
"name" => "test1",
], [
"formula" => [
"totalPoints" => 214.76,
],
"name" => "test2",
]],
],
], [
"lineupSet" => [
[[
"formula" => [
"totalPoints" => 205.71,
],
"name" => "test1",
], [
"formula" => [
"totalPoints" => 204.43,
],
"name" => "test2",
]],
],
], [
"lineupSet" => [
[[
"formula" => [
"totalPoints" => 205.48,
],
"name" => "test1",
], [
"formula" => [
"totalPoints" => 203.51,
],
"name" => "test2",
]],
],
]];
答案 0 :(得分:1)
您可以使用usort
根据自定义函数对数组进行排序。此函数确定给定totalPoints
的{{1}}:
lineupSet
要对降序进行排序(因此最大总点位于数组的第一个条目中),然后使用排序函数,当第二个值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;
}
大于第一个值时,该函数将返回一个正数,为负数较小时为数字,相同时为0:
totalPoints
最后,我们使用此函数调用function sort_points($a, $b) {
return sum_points($b) - sum_points($a);
}
并输出数组的第一个元素:
usort
输出:
usort($testArray, 'sort_points');
print_r($testArray[0]);