PHP

Group PHP Array Elements by a Specific Key

Learn an effective and common method to group items within an array of associative arrays based on the value of a specific key, useful for categorizing and structuring data.

<?php
$products = [
    ['id' => 1, 'category' => 'Electronics', 'name' => 'Laptop'],
    ['id' => 2, 'category' => 'Books', 'name' => 'Novel'],
    ['id' => 3, 'category' => 'Electronics', 'name' => 'Smartphone'],
    ['id' => 4, 'category' => 'Books', 'name' => 'Textbook'],
    ['id' => 5, 'category' => 'Electronics', 'name' => 'Monitor']
];

$groupedProducts = [];

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

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

            [1] => Array
                (
                    [id] => 3
                    [category] => Electronics
                    [name] => Smartphone
                )

            [2] => Array
                (
                    [id] => 5
                    [category] => Electronics
                    [name] => Monitor
                )

        )

    [Books] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [category] => Books
                    [name] => Novel
                )

            [1] => Array
                (
                    [id] => 4
                    [category] => Books
                    [name] => Textbook
                )

        )

)
*/
?>
How it works: This snippet demonstrates a widely used pattern for grouping elements in an array of associative arrays. It iterates through the original array and uses a specific key's value (e.g., 'category') to create new keys in a result array. Each new key then holds an array of all original elements that share that common key value, effectively categorizing your data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs