我目前正在寻找一种有效的方法来根据最高 -> 最低使用对数组/对象进行排序avgTotalPoints,然后根据字段中的排名放置数值rank。我查看了一些示例并能够相应地创建一个函数。然而,它现在正在发挥作用。我试图访问avgTotalPoints下面所示的排序函数,但我无法访问,因为数组是多深度的。关于如何实现这一目标有任何指导吗?function sortHighestToLowest($arr){ if (isset($arr) && !empty($arr)) { uasort($arr, function ($a, $b) { return $a['avgTotalPoints'] <=> $b['avgTotalPoints']; }); return array_reverse($arr); } return null;}JSON 输入{ "mlb": { "james": { "avgTotalPoints": 80.675, "avgPointsDifferential": -0.8112500000000002, "rank": null }, "mary": { "avgTotalPoints": 114.9875, "avgPointsDifferential": 6.262500000000003, "rank": null }, "lucas": { "avgTotalPoints": 66.825, "avgPointsDifferential": -9.10625, "rank": null }, "timothy": { "avgTotalPoints": 69.2625, "avgPointsDifferential": -19.14125, "rank": null }, "samantha": { "avgTotalPoints": 91.625, "avgPointsDifferential": -36.85000000000001, "rank": null } }, "nhl": { "samantha": { "avgTotalPoints": 82.20000000000002, "avgPointsDifferential": 15.005714285714289, "rank": null }, "peter": { "avgTotalPoints": 77.65714285714284, "avgPointsDifferential": -13.31857142857143, "rank": null }, "rick": { "avgTotalPoints": 91.61428571428571, "avgPointsDifferential": 11.217142857142859, "rank": null }, "bubba": { "avgTotalPoints": 119.60000000000001, "avgPointsDifferential": 28.13333333333334, "rank": null }, "james": { "avgTotalPoints": 90.18571428571428, "avgPointsDifferential": 10.915714285714285, "rank": null } }}
1 回答
鸿蒙传说
TA贡献1865条经验 获得超7个赞
由于您的数组包含多个要单独排序的子数组,因此您可以利用将array_map
排序应用于每个子数组。
执行此操作后,您可以简单地循环遍历同一子数组(通过引用)$rank
,同时递增变量并将其分配给每个条目。
另外,您不需要使用array_reverse
反转排序,只需反转<=>
比较的操作数即可。
function sortHighestToLowest(array $arr): array
{
return array_map(static function (array $entries): array {
uasort($entries, static function (array $entry1, array $entry2): int {
return $entry2['avgTotalPoints'] <=> $entry1['avgTotalPoints'];
});
$rank = 0;
foreach ($entries as &$entry) {
$entry['rank'] = ++$rank;
}
return $entries;
}, $arr);
}
- 1 回答
- 0 关注
- 97 浏览
添加回答
举报
0/150
提交
取消