PHP
Sort Associative Arrays by Multiple Columns in PHP
Learn how to sort a complex array of records based on the values of one or more specified keys, allowing for custom sort orders (ascending/descending) on each column.
$users = [
['name' => 'Alice', 'age' => 30, 'city' => 'New York'],
['name' => 'Bob', 'age' => 25, 'city' => 'Los Angeles'],
['name' => 'Charlie', 'age' => 30, 'city' => 'Chicago'],
['name' => 'David', 'age' => 25, 'city' => 'New York']
];
// Sort by 'age' (ASC), then by 'city' (ASC), then by 'name' (DESC)
array_multisort(
array_column($users, 'age'), SORT_ASC, SORT_NUMERIC,
array_column($users, 'city'), SORT_ASC, SORT_STRING,
array_column($users, 'name'), SORT_DESC, SORT_STRING,
$users
);
print_r($users);
How it works: The `array_multisort()` function is a powerful tool for sorting multi-dimensional arrays by multiple criteria. It takes an array of column values (extracted using `array_column()`), followed by sort order and type constants for each criterion. The original `$users` array is passed as the final argument, and it is sorted in-place based on the defined priority and type of each column.