Search code examples
phparraysmultidimensional-arraycriteria

PHP Multisort array on more than 2 criteria


I wrote a php script that will execute a full (dutch) soccer competition, based on parameters as Strength and moral.

After all rounds have been 'played', I use usort to define the end results.

These results are based on the 'Points' field. However, when two teams share the same number of points, further ranking has to be achieved by comparing the goal difference.

I tried to accomplish this sorting using first sorting om 'Points' and after that sorting om 'GoalDifference (GD)'. Unfortunately in the latter case goaldifference is sorted correctly but not the Points...

This is what the teams array looks like now:

    $teams = array
  (
    array(
        'Id' => 1,
        'Teamname' => 'Team 1,
        'Strength' => 22,
        'Moral' => 15,
        'Points' => 0,
        'Pro' => 0,
        'Contra'=> 0,
        'GD' => 0
    )    
}

Below the usort functions

    usort($teams, function($a, $b) {

    return $a['Points'] < $b['Points'];
});

    usort($teams, function($a, $b) {

    return $a['GD'] < $b['GD'];
});

So my question is, what is the best way to first sort on points and after that on goaldifference?

Kind regards,

Kees


Solution

  • You can build an more complex sort function where you check the columns in priority.

    usort($teams, function($a, $b) {
    
        if ($a["Points"] < $b["Points"]) return -1;
        if ($a["Points"] > $b["Points"]) return 1;
        if ($a['GD'] < $b['GD']) return -1;
        if ($a['GD'] > $b['GD']) return 1;
    
        return 0;
    });