← Back to all snippets
PHP

Sort Associative Arrays by Multiple Fields

Discover how to efficiently sort a list of associative arrays or objects in PHP by multiple keys (e.g., primary then secondary) using `array_multisort` for complex ordering.

<?php
$products = [
    ['name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
    ['name' => 'T-Shirt', 'category' => 'Apparel', 'price' => 25],
    ['name' => 'Mouse', 'category' => 'Electronics', 'price' => 30],
    ['name' => 'Jeans', 'category' => 'Apparel', 'price' => 60]
];

// Extract columns 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, SORT_STRING,
    $prices,     SORT_ASC, SORT_NUMERIC,
    $products
);

print_r($products);
?>
How it works: This snippet illustrates how to sort an array of associative arrays by multiple criteria using PHP's powerful `array_multisort` function. We first extract the 'category' and 'price' columns into separate arrays using `array_column`. Then, `array_multisort` is called with these extracted arrays as primary and secondary sort keys, followed by the original `$products` array, which gets sorted in place. This allows for complex sorting, in this case, sorting by category alphabetically and then by price from lowest to highest within each category.

Need help integrating this into your project?

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

Hire DigitalCodeLabs