Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Sort Multidimensional Array Based on Multiple Criteria [duplicate]

I have a multidimensional array that looks like:

$arr=Array
(
    [0] => Array
        (
            [0] => TEAM1
            [1] => 3
            [2] => 0
            [3] => 422.47
            [4] => 192.62
        )

    [1] => Array
        (
            [0] => TEAM2
            [1] => 2
            [2] => 1
            [3] => 402.14
            [4] => 210.70
        )

    [2] => Array
        (
            [0] => TEAM3
            [1] => 3
            [2] => 0
            [3] => 376.79
            [4] => 174.64
        )
)

The 5 columns relate to Team Name, # wins, # losses, # of points for, # of points against.

How would I sort $arr by column 1 (# Wins) (Descending), then column 2 (# Losses) (Ascending), and then column 3 (# of Pts For) (Descending)

like image 293
Bijan Avatar asked Sep 06 '25 15:09

Bijan


1 Answers

I found a solution that uses array_multisort()

foreach ($arr as $key => $row) {
    $wins[$key] = $row[1]; 
    $losses[$key] = $row[2];
    $ptsfor[$key] = $row[3];
}
array_multisort($wins, SORT_DESC, $losses, SORT_ASC, $ptsfor, SORT_DESC, $arr);
like image 142
Bijan Avatar answered Sep 08 '25 11:09

Bijan