PHP
Sort an Array of Associative Arrays by a Nested Key
Master sorting complex PHP arrays (array of objects/associative arrays) based on the value of a specific nested key using `usort`.
<?php
$users = [
['id' => 101, 'name' => 'Alice', 'details' => ['age' => 30, 'city' => 'New York']],
['id' => 103, 'name' => 'Charlie', 'details' => ['age' => 25, 'city' => 'Chicago']],
['id' => 102, 'name' => 'Bob', 'details' => ['age' => 35, 'city' => 'Los Angeles']],
];
// Sort users by their age in ascending order
usort($users, function($a, $b) {
return $a['details']['age'] <=> $b['details']['age']; // Spaceship operator for comparison
});
print_r($users);
/*
Output will be:
Array
(
[0] => Array
(
[id] => 103
[name] => Charlie
[details] => Array
(
[age] => 25
[city] => Chicago
)
)
[1] => Array
(
[id] => 101
[name] => Alice
[details] => Array
(
[age] => 30
[city] => New York
)
)
[2] => Array
(
[id] => 102
[name] => Bob
[details] => Array
(
[age] => 35
[city] => Los Angeles
)
)
)
*/
?>
How it works: This snippet demonstrates how to sort a multidimensional array (specifically, an array of associative arrays) based on a value located within a nested key. It utilizes the `usort` function, which allows for custom sorting logic defined by a callback function. The spaceship operator (`<=>`) efficiently compares the 'age' values from the 'details' subarray of each user, returning -1, 0, or 1 to indicate their relative order.