Sorting a multidimensional array based on multiple values

I have the following array, which I need to sort from the highest score to the lowest.

Array
(
    [0] => Array
        (
            [team id] => 5
            [score] => 52
            [fouls] => 0
        )

    [1] => Array
        (
            [team id] => 4
            [score] => 47
            [fouls] => 0
        )

    [2] => Array
        (
            [team id] => 8
            [score] => 46
            [fouls] => 6
        )

    [3] => Array
        (
            [team id] => 1
            [score] => 46
            [fouls] => 5
        )

    [4] => Array
        (
            [team id] => 9
            [score] => 46
            [fouls] => 3
        )

)

The above array has already been sorted using this function:

function sortByOrder($a, $b){
    $Return = $b['score'] - $a['score'];
    return $Return;
}

usort($Array, 'sortByOrder');

It seems to work fine, as the array with the highest result goes up the list.

However, some teams have equal scores, but have committed some fouls. How can I adjust the function to also take fouls into account when the score is a different score? The team with the lowest fouls should be placed higher.

Waiting for creative solutions!

Thanks in advance.

+3
source share
2 answers

You just need to update your function sortByOrder().

Basically:

function sortByOrder($a, $b){
  if ($b['score'] == $a['score'])
    return $a['fouls'] - $b['fouls'];
  else
    return $b['score'] - $a['score'];
}
+7
source

, usort , .

, , , :

function sortByOrder($a, $b) {
    if ($a['score'] == $b['score']) {
        return ($a['fouls'] < $b['fouls']) ? -1 : 1;;
    }
    return ($a['score'] < $b['score']) ? -1 : 1;
}

N.B , , , , , -1 (a b) 1 (a , b).

0

All Articles