For a current project I’m working on, I’ve had to rank a list of teams based on their win-loss-tie record within their division. I searched the web but was unable to find anyone who had done this and posted an example so I figured I’d post my process. If you have corrections or improvements for this, please feel free to comment.
The code assumes that you have an array of team objects that each have a win/loss/tie property. As an example, I’ve got an array of five teams such that:
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Team 1
[wins] => 5
[losses] => 6
[ties] => 3
)[1] => stdClass Object
(
[id] => 2
[name] => Team 2
[wins] => 4
[losses] => 8
[ties] => 4
)[2] => stdClass Object
(
[id] => 3
[name] => Team 3
[wins] => 2
[losses] => 9
[ties] => 6
)[3] => stdClass Object
(
[id] => 4
[name] => Team 4
[wins] => 4
[losses] => 9
[ties] => 4
)[4] => stdClass Object
(
[id] => 5
[name] => Team 5
[wins] => 4
[losses] => 9
[ties] => 5
)
)
We’re going to use usort to sort the array based on each team’s win/loss/tie record. First, we need to write our usort method:
function sort_win_loss($team1, $team2) {
if($team1->wins > $team2->wins) {
return -1;
} else if($team1->wins < $team2->wins) {
return 1;
} else if($team1->wins == $team2->wins) {
if($team1->losses>$team2->losses) {
return 1;
} else if($team1->losses<$team2->losses) {
return -1;
} else if($team1->losses==$team2->losses){
if($team1->ties>$team2->ties) {
return -1;
} else if($team1->ties<$team2->ties) {
return 1;
} else {
return 0;
}
}
}
return 0;
}
Lastly, we provide our array of teams to the usort and get our sorted list back:
usort($teams, “sort_win_loss”);
// After the usort, the teams will be ranked as
// 1) Team 1
// 2) Team 2
// 3) Team 5
// 4) Team 4
// 5) Team 3