PHP
Custom Sorting Associative Arrays by Key
Implement custom sorting for an array of associative arrays or objects in PHP, allowing you to sort by one or more specified keys with flexible order.
/**
* Sorts an array of associative arrays by a given key (or multiple keys).
* @param array $array The array to sort.
* @param string|array $key The key(s) to sort by. Can be a string or an array of strings.
* @param int $order The sort order (SORT_ASC or SORT_DESC). Applies to all keys if multiple.
* @return array The sorted array.
*/
function sortAssociativeArrayByKey(array $array, string|array $key, int $order = SORT_ASC): array {
if (empty($array)) {
return [];
}
// Convert single key to an array for uniform processing
$keys = is_string($key) ? [$key] : $key;
usort($array, function($a, $b) use ($keys, $order) {
foreach ($keys as $k) {
$valA = $a[$k] ?? null; // Use null coalescing for safety
$valB = $b[$k] ?? null;
if ($valA === $valB) {
continue; // Values are equal, move to next key
}
// Handle numeric vs. string comparison
if (is_numeric($valA) && is_numeric($valB)) {
$cmp = $valA <=> $valB;
} else {
$cmp = strcasecmp((string)$valA, (string)$valB);
}
return ($order === SORT_ASC) ? $cmp : -$cmp;
}
return 0; // All keys were equal
});
return $array;
}
$users = [
['id' => 1, 'name' => 'Alice', 'age' => 30],
['id' => 2, 'name' => 'Bob', 'age' => 25],
['id' => 3, 'name' => 'Charlie', 'age' => 35],
['id' => 4, 'name' => 'Aaron', 'age' => 25],
];
$sortedByName = sortAssociativeArrayByKey($users, 'name', SORT_ASC);
// $sortedByName will be sorted by name: Aaron, Alice, Bob, Charlie
$sortedByAgeThenName = sortAssociativeArrayByKey($users, ['age', 'name'], SORT_ASC);
// $sortedByAgeThenName will be sorted by age (25, 25, 30, 35) then by name for equal ages (Aaron, Bob)
How it works: This function sorts an array of associative arrays based on one or more specified keys. It uses `usort` with a custom comparison function. The comparison function iterates through the provided keys, comparing values. If values for a key are equal, it moves to the next key for secondary sorting. It supports ascending or descending order and handles both numeric and string comparisons robustly.