PHP
Custom Sort Associative Arrays by Multiple Keys
Discover how to sort complex associative arrays in PHP using `usort` with a custom comparison function, allowing flexible ordering by one or more keys.
$users = [
['name' => 'Alice', 'age' => 30, 'score' => 95],
['name' => 'Bob', 'age' => 25, 'score' => 88],
['name' => 'Charlie', 'age' => 30, 'score' => 92],
['name' => 'David', 'age' => 25, 'score' => 95],
];
// Sort by age (ascending), then by score (descending)
usort($users, function($a, $b) {
// Primary sort: age ascending
if ($a['age'] !== $b['age']) {
return $a['age'] <=> $b['age'];
}
// Secondary sort: score descending
return $b['score'] <=> $a['score'];
});
// var_dump($users);
/*
array(4) {
[0]=> array(3) { ["name"]=> "David", ["age"]=> 25, ["score"]=> 95 }
[1]=> array(3) { ["name"]=> "Bob", ["age"]=> 25, ["score"]=> 88 }
[2]=> array(3) { ["name"]=> "Alice", ["age"]=> 30, ["score"]=> 95 }
[3]=> array(3) { ["name"]=> "Charlie", ["age"]=> 30, ["score"]=> 92 }
}
*/
How it works: This example demonstrates how to perform a multi-criteria sort on an array of associative arrays using `usort`. It takes a custom comparison function that defines the sorting logic. Here, it sorts users primarily by `age` in ascending order, and for users with the same age, it then sorts them by `score` in descending order, offering powerful control over data ordering.