数组排序并保持按键的值
问题描述:
我有一个数组,看起来像这样:
I have an array that looks like this:
Array
(
[team1] => Array
(
[points] => 10
[players] => Array
(
...
)
)
[team2] => Array
(
[points] => 23
[players] => Array
(
...
)
)
... many more teams
)
和我想点每支球队都有数以球队进行排序。我曾尝试这样的:
and I would like to sort the teams by the number of points each team has. I have tried this:
function sort_by_points($a,$b)
{
if ($a['points']==$b['points']) return 0;
return ($a['points']<$b['points'])?1:-1;
}
usort($this->wordswithdata, "sortbycount");
但这种方法会覆盖包含teamnames和返回键:
But that approach overrides the keys containing the teamnames and returns:
Array
(
[0] => Array
(
[points] => 23
[players] => Array
(
...
)
)
[1] => Array
(
[points] => 10
[players] => Array
(
...
)
)
etc...
)
有什么办法没有覆盖teamnames作为数组键的数组进行排序?
Is there any way to sort the array without overwriting the teamnames as the array keys?
答
使用 uasort 功能,应该保持键=>值的关联不变。
Use the uasort function, that should keep the key => value associations intact.
(侧面说明:你可以做返回$一个['点'] - $ B ['点']
而不是IFS)
(side note: you can do return $a['points'] - $b['points']
instead of the ifs)