PHP
Sort Array of Associative Arrays by Multiple Keys
Discover how to sort an array of complex data structures (associative arrays or objects) using multiple criteria or keys in PHP, leveraging the powerful array_multisort function.
<?php
$products = [
['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
['name' => 'Shirt', 'price' => 30, 'category' => 'Apparel'],
['name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
['name' => 'Jeans', 'price' => 60, 'category' => 'Apparel'],
];
// Prepare arrays for sorting by category (ascending) then by price (descending)
$categories = array_column($products, 'category');
$prices = array_column($products, 'price');
// Sort the original array using the prepared columns
array_multisort(
$categories, SORT_ASC, SORT_STRING,
$prices, SORT_DESC, SORT_NUMERIC,
$products
);
echo "Products sorted by Category (ASC) then Price (DESC):
";
print_r($products);
?>
How it works: This snippet showcases `array_multisort`, a versatile PHP function for sorting multi-dimensional arrays or multiple arrays simultaneously. It first extracts the 'category' and 'price' columns into separate arrays using `array_column`. Then, `array_multisort` is called, specifying the sorting order (ascending/descending) and type (string/numeric) for each column, and finally passing the original `$products` array to be sorted in place. This is crucial for presenting tabular data with complex sorting requirements.