PHP

Sorting PHP Arrays of Associative Arrays by Multiple Keys

Sort a complex PHP array containing multiple associative arrays by one or more specified keys, in ascending or descending order. Useful for structured data.

<?php
$products = [
    ['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
    ['name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
    ['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
    ['name' => 'Book A', 'price' => 30, 'category' => 'Books'],
    ['name' => 'Book B', 'price' => 20, 'category' => 'Books'],
    ['name' => 'Monitor', 'price' => 300, 'category' => 'Electronics']
];

// Method 1: Using array_multisort (best for simple, multiple-column sorts)
$category = array_column($products, 'category');
$price = array_column($products, 'price');

array_multisort(
    $category, SORT_ASC,      // Sort by category ascending
    $price,    SORT_ASC,      // Then by price ascending within each category
    $products                  // The array to sort
);

echo "Sorted by Category (ASC) then Price (ASC):
";
print_r($products);

// Method 2: Using usort with a custom comparison function (more flexible for complex logic)
$products2 = [
    ['name' => 'Laptop', 'price' => 1200, 'category' => 'Electronics'],
    ['name' => 'Mouse', 'price' => 25, 'category' => 'Electronics'],
    ['name' => 'Keyboard', 'price' => 75, 'category' => 'Electronics'],
    ['name' => 'Book A', 'price' => 30, 'category' => 'Books'],
    ['name' => 'Book B', 'price' => 20, 'category' => 'Books'],
    ['name' => 'Monitor', 'price' => 300, 'category' => 'Electronics']
];

usort($products2, function($a, $b) {
    // Sort by category (ASC)
    $categoryCompare = strcmp($a['category'], $b['category']);
    if ($categoryCompare !== 0) {
        return $categoryCompare;
    }

    // If categories are the same, sort by price (DESC)
    if ($a['price'] == $b['price']) {
        return 0;
    }
    return ($a['price'] < $b['price']) ? 1 : -1; // Price DESC
});

echo "
Sorted by Category (ASC) then Price (DESC):
";
print_r($products2);
?>
How it works: This snippet demonstrates two powerful methods for sorting an array of associative arrays by multiple criteria. `array_multisort` is excellent for sorting by values extracted from specific columns, offering a concise way to define primary and secondary sort orders. `usort`, with a custom comparison function, provides greater flexibility, allowing for more complex sorting logic, including different directions (ASC/DESC) for various keys and custom comparisons (e.g., case-insensitive strings). Both are essential for organizing complex datasets based on specific business rules.

Need help integrating this into your project?

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

Hire DigitalCodeLabs