PHP

Group Associative Array Items by a Specific Key

Organize an array of associative arrays into groups based on a common key's value, creating nested arrays for better data structure and access.

<?php
$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
    ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
    ['id' => 3, 'name' => 'Shirt', 'category' => 'Apparel', 'price' => 40],
    ['id' => 4, 'name' => 'Jeans', 'category' => 'Apparel', 'price' => 60],
    ['id' => 5, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
];

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

print_r($groupedProducts);
/*
Expected Output:
Array
(
    [Electronics] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Laptop
                    [category] => Electronics
                    [price] => 1200
                )

            [1] => Array
                (
                    [id] => 2
                    [name] => Mouse
                    [category] => Electronics
                    [price] => 25
                )

            [2] => Array
                (
                    [id] => 5
                    [name] => Keyboard
                    [category] => Electronics
                    [price] => 75
                )

        )

    [Apparel] => Array
        (
            [0] => Array
                (
                    [id] => 3
                    [name] => Shirt
                    [category] => Apparel
                    [price] => 40
                )

            [1] => Array
                (
                    [id] => 4
                    [name] => Jeans
                    [category] => Apparel
                    [price] => 60
                )

        )

)
*/
How it works: This snippet demonstrates a common pattern for organizing data: grouping a flat list of associative arrays into a multi-dimensional array based on a shared key. It iterates through each product and uses the 'category' value as the key for the new grouped array. If a category key doesn't exist yet, it's initialized as an empty array before the current product is added, making the data easier to access and display 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