Skip to content
Advertisement

Sort array and keep values of keys

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");

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...
)

Is there any way to sort the array without overwriting the teamnames as the array keys?

Advertisement

Answer

Use the uasort function, that should keep the key => value associations intact.

(side note: you can do return $a['points'] - $b['points'] instead of the ifs)

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement