我有一个看起来像这样的数组:
$this->wordswithdata = [
'team1' => [
'points' => 10,
'players' => [],
],
'team2' => [
'points' => 23,
'players' => []
]
];
我想按照每支球队的得分从高到低对球队进行排序。我已经尝试过这个:
function sort_by_points($a,$b)
{
if ($a['points'] == $b['points']) return 0;
return ($a['points'] < $b['points']) ? 1 : -1;
}
usort($this->wordswithdata, "sortbycount");
但该方法会覆盖包含团队名称的键并返回:
[
0 => [
'points' => 23,
'players' => []
],
1 => [
'points' => 10,
'players' => [],
]
]
有没有什么方法可以对数组进行排序而不丢失作为数组键的团队名称?
Use the uasort http://php.net/manual/en/function.uasort.php函数,应该保持 key => value 关联完整。
(旁注:你可以做return $a['points'] - $b['points']
而不是 ifs,或者从 php7 开始飞船<=>操作员 https://www.php.net/manual/en/language.operators.comparison.php,感谢 mbomb007 的更新)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)