4

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)

Bijan
  • 7,737
  • 18
  • 89
  • 149

3 Answers3

8

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);
Bijan
  • 7,737
  • 18
  • 89
  • 149
0

Instead you can simply use usort function like as

usort($arr, function($a,$b){
    if($a[1] != $b[1])
        return $b[1] - $a[1];
    else if($a[2] != $b[2])
        return $a[2] - $b[2];
    else if($a[3] != $b[3])
        return $b[3] - $a[3];
});

Or you can use it like as

usort($arr,function($a,$b){
    $c = $b[1] - $a[1];
    $c .= $a[2] - $b[2];
    $c .= $b[3] - $a[3];
    return $c;
});
Narendrasingh Sisodia
  • 21,247
  • 6
  • 47
  • 54
  • I think my method of using `array_multisort()` is easier to follow since it clearly shows `SORT_DESC` or `SORT_ASC` – Bijan Sep 23 '15 at 05:27
  • Why to use loop and function if it can be done easily within single function – Narendrasingh Sisodia Sep 23 '15 at 05:28
  • Looks pretty similar to https://stackoverflow.com/a/31693963/2943403 but I don't know if I like the concatenation of positive and potentially negative numbers as a string. – mickmackusa Jun 03 '20 at 06:43
0

You can use this function

    function sort_array($array, $sortkey, $order)
    {
        if ($order == "DESC")
            $or = "arsort";
        else
            $or = "asort";
        foreach ($array as $key => $array_row)
        {
            $sort_values[$key] = $array_row[$sortkey];
        }
        $or($sort_values);
        reset($sort_values);
        while (list ($arr_key, $arr_val) = each($sort_values))
        {
            $sorted_arr[] = $array[$arr_key];
        }
        return $sorted_arr;
    }
PravinS
  • 2,640
  • 3
  • 21
  • 25