php – 排序数组并保持键值

前端之家收集整理的这篇文章主要介绍了php – 排序数组并保持键值前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个如下的数组:
Array
(
    [team1] => Array
        (
            [points] => 10
            [players] => Array
                (
                     ...
                )
        )

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

    ... many more teams
)

我想按照每个队伍的分数排序队伍.我试过这个:

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

usort($this->wordswithdata,"sortbycount");

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

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

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

    etc...
)

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

使用 uasort功能,应该保持键=>价值关联完好无损.

(旁注:你可以返回$a [‘points’] – $b [‘points’]而不是ifs)

猜你在找的PHP相关文章