PHP
Custom Sorting Associative Arrays by Multiple Keys in PHP
Learn to sort an array of associative arrays (or objects) in PHP based on one or more custom criteria using `usort()` and a comparison callback function.
<?php
/**
* Sorts an array of associative arrays by a specified key and order.
* Can handle multiple sort criteria.
*
* @param array $data The array to sort.
* @param array $sortFields An array of arrays, e.g., [['field' => 'name', 'order' => 'ASC'], ['field' => 'age', 'order' => 'DESC']]
* @return array The sorted array.
*/
function sortAssociativeArray(array $data, array $sortFields): array
{
usort($data, function ($a, $b) use ($sortFields) {
foreach ($sortFields as $sortField) {
$field = $sortField['field'];
$order = strtoupper($sortField['order'] ?? 'ASC'); // Default to ASC
if (!isset($a[$field]) || !isset($b[$field])) {
// Handle cases where field might be missing (e.g., throw error, skip, or default comparison)
continue;
}
$cmp = ($a[$field] <=> $b[$field]); // Spaceship operator (PHP 7+)
if ($cmp !== 0) {
return ($order === 'DESC') ? -$cmp : $cmp;
}
}
return 0; // Elements are equal based on all criteria
});
return $data;
}
// Example Usage:
$users = [
['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
['name' => 'Bob', 'age' => 25, 'city' => 'London'],
['name' => 'Charlie', 'age' => 35, 'city' => 'Paris'],
['name' => 'Alice', 'age' => 28, 'city' => 'London'],
['name' => 'Bob', 'age' => 40, 'city' => 'New York'],
];
echo "Original Users:
";
foreach ($users as $user) {
echo json_encode($user) . "
";
}
// Sort by name ASC, then by age DESC
$sortedUsers = sortAssociativeArray($users, [
['field' => 'name', 'order' => 'ASC'],
['field' => 'age', 'order' => 'DESC']
]);
echo "
Sorted Users (Name ASC, Age DESC):
";
foreach ($sortedUsers as $user) {
echo json_encode($user) . "
";
}
// Sort by age ASC
$sortedByAge = sortAssociativeArray($users, [['field' => 'age', 'order' => 'ASC']]);
echo "
Sorted Users (Age ASC):
";
foreach ($sortedByAge as $user) {
echo json_encode($user) . "
";
}
?>
How it works: This snippet provides a flexible function to sort an array of associative arrays based on one or more specified keys and their respective sorting orders (ascending or descending). It uses PHP's `usort()` function with a custom comparison callback, leveraging the spaceship operator (`<=>`) for concise comparisons. This is extremely useful for displaying tabular data or lists in a user-defined order.