How can PHP functions be structured to handle multiple criteria for ranking teams in a league, such as points, direct encounters, and goal differences?
To handle multiple criteria for ranking teams in a league, such as points, direct encounters, and goal differences, you can create a custom PHP function that takes in the necessary data (points, direct encounters, goal differences) for each team and calculates the overall ranking based on these criteria. The function should compare teams based on each criterion in order of importance and return the final ranking.
function rankTeams($teams) {
usort($teams, function($a, $b) {
if ($a['points'] != $b['points']) {
return $b['points'] - $a['points']; // Sort by points
} elseif ($a['direct_encounters'] != $b['direct_encounters']) {
return $b['direct_encounters'] - $a['direct_encounters']; // Sort by direct encounters
} else {
return $b['goal_difference'] - $a['goal_difference']; // Sort by goal difference
}
});
return $teams;
}
// Example data for teams
$team1 = ['name' => 'Team A', 'points' => 15, 'direct_encounters' => 3, 'goal_difference' => 5];
$team2 = ['name' => 'Team B', 'points' => 15, 'direct_encounters' => 2, 'goal_difference' => 8];
$team3 = ['name' => 'Team C', 'points' => 12, 'direct_encounters' => 1, 'goal_difference' => 3];
$teams = [$team1, $team2, $team3];
// Rank teams based on multiple criteria
$rankedTeams = rankTeams($teams);
// Output the ranked teams
foreach ($rankedTeams as $rank => $team) {
echo ($rank + 1) . '. ' . $team['name'] . PHP_EOL;
}