How can PHP be used to sort data based on multiple criteria like points and goal difference?
To sort data based on multiple criteria like points and goal difference in PHP, you can use the `usort` function along with a custom comparison function. The custom comparison function should compare the points first, and if they are equal, then compare the goal difference. This will allow you to sort the data based on both criteria.
$data = [
['team' => 'Team A', 'points' => 15, 'goal_difference' => 10],
['team' => 'Team B', 'points' => 12, 'goal_difference' => 8],
['team' => 'Team C', 'points' => 15, 'goal_difference' => 5],
// Add more teams as needed
];
usort($data, function($a, $b) {
if ($a['points'] == $b['points']) {
return $b['goal_difference'] - $a['goal_difference'];
}
return $b['points'] - $a['points'];
});
foreach ($data as $team) {
echo $team['team'] . ' - Points: ' . $team['points'] . ', Goal Difference: ' . $team['goal_difference'] . PHP_EOL;
}