PHP

Sort an Array of Associative Arrays by Multiple Keys

Master sorting complex PHP arrays containing associative data by applying multiple sorting criteria (e.g., primary and secondary keys) for highly organized data presentation.

$products = [
    ['name' => 'Apple', 'category' => 'Fruit', 'price' => 1.50],
    ['name' => 'Banana', 'category' => 'Fruit', 'price' => 0.75],
    ['name' => 'Carrot', 'category' => 'Vegetable', 'price' => 1.20],
    ['name' => 'Orange', 'category' => 'Fruit', 'price' => 1.00],
    ['name' => 'Broccoli', 'category' => 'Vegetable', 'price' => 2.00]
];

// Get arrays of 'category' and 'price' for sorting
$categories = array_column($products, 'category');
$prices = array_column($products, 'price');

// Sort by category (ASC), then by price (ASC)
array_multisort($categories, SORT_ASC, $prices, SORT_ASC, $products);

print_r($products);
/*
Expected output:
Array
(
    [0] => Array ( [name] => Apple [category] => Fruit [price] => 1.5 )
    [1] => Array ( [name] => Banana [category] => Fruit [price] => 0.75 )
    [2] => Array ( [name] => Orange [category] => Fruit [price] => 1 )
    [3] => Array ( [name] => Carrot [category] => Vegetable [price] => 1.2 )
    [4] => Array ( [name] => Broccoli [category] => Vegetable [price] => 2 )
)
*/
How it works: This snippet demonstrates how to sort an array of associative arrays by multiple keys using `array_multisort`. First, `array_column` is used to extract the values of the primary and secondary sorting keys into separate arrays. Then, `array_multisort` is called, passing these extracted arrays along with their desired sort orders, and finally the original `$products` array itself. This sorts the `$products` array in place, first by 'category' and then by 'price' for items within the same category.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs