排序数组并保持键的值

acr*_*uui 23 php arrays sorting

我有一个看起来像这样的数组:

Array
(
    [team1] => Array
        (
            [points] => 10
            [players] => Array
                (
                     ...
                )
        )

    [team2] => Array
        (
            [points] => 23
            [players] => Array
                (
                     ...
                )
        )

    ... many more teams
)
Run Code Online (Sandbox Code Playgroud)

我希望按照每支球队的得分数对球队进行排序.我试过这个:

function sort_by_points($a,$b)
{
    if ($a['points']==$b['points']) return 0;
        return ($a['points']<$b['points'])?1:-1;
}

usort($this->wordswithdata, "sortbycount");
Run Code Online (Sandbox Code Playgroud)

但是这种方法会覆盖包含团队名称和返回的键:

Array
(
    [0] => Array
        (
            [points] => 23
            [players] => Array
                (
                     ...
                )
        )

    [1] => Array
        (
            [points] => 10
            [players] => Array
                (
                     ...
                )
        )

    etc...
)
Run Code Online (Sandbox Code Playgroud)

有没有办法排序数组而不覆盖团队名作为数组键?

com*_*857 24

使用uasort函数,该函数应保持key => value关联不变.

(旁注:你可以return $a['points'] - $b['points']代替ifs)


Sho*_*hoe 16

你可以使用uasort:

uasort($array, function($a, $b) {
    return $a['points'] - $b['points'];
});
Run Code Online (Sandbox Code Playgroud)

此函数使用用户定义的比较函数对数组进行排序,以使数组索引与它们关联的数组元素保持相关性.