PHP

Grouping an Array of Associative Arrays by a Specific Key

Learn how to effectively group an array of associative arrays or objects based on the value of a specific key in PHP, similar to a SQL GROUP BY clause, creating nested arrays.

<?php

$products = [
    ['category' => 'Electronics', 'name' => 'Laptop', 'price' => 1200],
    ['category' => 'Books', 'name' => 'PHP Manual', 'price' => 45],
    ['category' => 'Electronics', 'name' => 'Smartphone', 'price' => 800],
    ['category' => 'Books', 'name' => 'Cookbook', 'price' => 30],
    ['category' => 'Electronics', 'name' => 'Headphones', 'price' => 150]
];

$groupedProducts = [];
foreach ($products as $product) {
    $category = $product['category'];
    if (!isset($groupedProducts[$category])) {
        $groupedProducts[$category] = [];
    }
    $groupedProducts[$category][] = $product;
}

print_r($groupedProducts);

/*
Output:
Array
(
    [Electronics] => Array
        (
            [0] => Array
                (
                    [category] => Electronics
                    [name] => Laptop
                    [price] => 1200
                )

            [1] => Array
                (
                    [category] => Electronics
                    [name] => Smartphone
                    [price] => 800
                )

            [2] => Array
                (
                    [category] => Electronics
                    [name] => Headphones
                    [price] => 150
                )

        )

    [Books] => Array
        (
            [0] => Array
                (
                    [category] => Books
                    [name] => PHP Manual
                    [price] => 45
                )

            [1] => Array
                (
                    [category] => Books
                    [name] => Cookbook
                    [price] => 30
                )

        )

)
*/
How it works: This snippet demonstrates how to group a list of associative arrays (or objects) based on the value of a specific key. It iterates through the original array and uses the value of the 'category' key to create new keys in a `groupedProducts` array. If a category key doesn't exist yet, it's initialized as an empty array, and then the current product is added to that category's array. This effectively organizes data, making it easier to process or display items by category.

Need help integrating this into your project?

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

Hire DigitalCodeLabs