PHP
Sort an Array of Associative Arrays by a Specific Key
Learn how to sort an array containing multiple associative arrays based on the value of a chosen key, allowing for both ascending and descending order, essential for data ordering.
function sortArrayOfAssociativeArrays(array &$array, string $key, string $order = 'ASC'): void
{
usort($array, function ($a, $b) use ($key, $order) {
if (!isset($a[$key]) || !isset($b[$key])) {
return 0; // Handle cases where key might be missing
}
$valueA = $a[$key];
$valueB = $b[$key];
if (is_numeric($valueA) && is_numeric($valueB)) {
return $order === 'ASC' ? ($valueA <=> $valueB) : ($valueB <=> $valueA);
} else {
return $order === 'ASC' ? strcasecmp($valueA, $valueB) : strcasecmp($valueB, $valueA);
}
});
}
$users = [
['name' => 'Alice', 'age' => 30],
['name' => 'Bob', 'age' => 25],
['name' => 'Charlie', 'age' => 35],
];
sortArrayOfAssociativeArrays($users, 'age', 'ASC');
// var_dump($users);
// Expected to be sorted by age: Bob, Alice, Charlie
sortArrayOfAssociativeArrays($users, 'name', 'DESC');
// var_dump($users);
// Expected to be sorted by name descending: Charlie, Bob, Alice
How it works: The `sortArrayOfAssociativeArrays` function uses `usort` to sort the input array in-place. A custom comparison function is provided that compares the values of the specified `$key` for two array elements (`$a` and `$b`). It intelligently handles both numeric and string comparisons and allows specifying 'ASC' or 'DESC' order for sorting. The spaceship operator (`<=>`) is used for concise numeric comparisons.