PHP
Sorting Multi-Dimensional PHP Arrays by Key
Discover how to sort complex PHP arrays of associative arrays (e.g., list of users) by a specific key's value using `usort` and a custom comparison function for precise ordering.
<?php
$users = [
['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
['name' => 'Bob', 'age' => 24, 'city' => 'London'],
['name' => 'Charlie', 'age' => 35, 'city' => 'Paris'],
['name' => 'David', 'age' => 24, 'city' => 'Tokyo']
];
// Sort users by age in ascending order
usort($users, function($a, $b) {
return $a['age'] <=> $b['age']; // Spaceship operator for comparison
});
echo "Sorted by Age (Ascending):
";
print_r($users);
// Sort users by name in descending order
usort($users, function($a, $b) {
return $b['name'] <=> $a['name']; // Swap $a and $b for descending
});
echo "
Sorted by Name (Descending):
";
print_r($users);
?>
How it works: The `usort()` function sorts an array by values using a user-defined comparison function. The callback function accepts two elements from the array (`$a` and `$b`) and should return an integer less than, equal to, or greater than zero if the first argument is considered to be respectively less than, equal to, or greater than the second. The spaceship operator (`<=>`) simplifies this comparison logic introduced in PHP 7.