Search code examples
phparrayssortingmultidimensional-array

Sort an array of single-element arrays by float value


I have this array and I want to sort it (ASC)?

$stand_array[$player_name][$player_points] = $player_rank;

print_r

Array
(
[Player1] => Array
    (
        [50] => 5.7
    )

[Player2] => Array
    (
        [40] => 4.2
    )

[Player3] => Array
    (
        [30] => 3.7
    )

[Player4] => Array
    (
        [20] => 2.3
    )

[Player5] => Array
    (
        [10 => 1.5
    )

[Player6] => Array
    (
        [60] => 6.3
    )
)

Would you like to help me to solve this array on $player_rank (ASC)?

NB: I tried this function, but it did not work:

function sortByOrder($a, $b) {
    return $a[$player_rank] - $b[$player_rank];
}
usort($myArray, 'sortByOrder');

Solution

  • The variable $player_rank is not visible from the sortByOrder function scope. Also, the indexes is different in each player array, so you need to access it like this:

    function sortByOrder($a, $b) 
    { 
        $a = end($a);
        $b = end($b);
    
        if ($a == $b) 
        {
           return 0;
        }
    
        return ($a < $b) ? -1 : 1;
    }
    usort($myArray, 'sortByOrder');
    

    And if you want to save keys in $myArray then you must use the uasort function instead of usort.