PHP
Custom Sort Associative Array by Nested Key
Learn to sort an array of associative arrays or objects based on a specific key's value, including nested keys, using PHP's `uasort` with a custom comparison function.
<?php
$users = [
['id' => 3, 'name' => 'Alice', 'details' => ['age' => 30, 'city' => 'New York']],
['id' => 1, 'name' => 'Bob', 'details' => ['age' => 25, 'city' => 'London']],
['id' => 2, 'name' => 'Charlie', 'details' => ['age' => 35, 'city' => 'Paris']],
];
// Sort by 'name' in ascending order
uasort($users, function($a, $b) {
return $a['name'] <=> $b['name']; // PHP 7+ spaceship operator
});
echo "Sorted by name:
";
print_r($users);
// Sort by 'age' (nested in 'details') in descending order
uasort($users, function($a, $b) {
return $b['details']['age'] <=> $a['details']['age']; // Descending order
});
echo "
Sorted by age (descending):
";
print_r($users);
// Sort by 'city' (nested in 'details') in ascending order
uasort($users, function($a, $b) {
return $a['details']['city'] <=> $b['details']['city'];
});
echo "
Sorted by city:
";
print_r($users);
?>
How it works: This snippet demonstrates how to sort an array of associative arrays while preserving key-value associations, using `uasort`. The `uasort` function takes the array and a user-defined comparison function. This anonymous function receives two elements (`$a`, `$b`) from the array and returns -1, 0, or 1 based on their relative order. The example shows sorting by a direct key ('name') and by a nested key ('age', 'city'), illustrating flexibility in defining custom sorting logic with the PHP 7+ spaceship operator (`<=>`).