PHP

Group Associative Arrays by a Key in PHP

Efficiently group a flat list of associative arrays into a multi-dimensional array, indexed by the value of a specified key, perfect for organizing data.

<?php
function group_by_key(array $array, string $key): array
{
    $grouped = [];
    foreach ($array as $item) {
        if (isset($item[$key])) {
            $grouped[$item[$key]][] = $item;
        }
    }
    return $grouped;
}

$products = [
    ['id' => 1, 'category' => 'Electronics', 'name' => 'Laptop'],
    ['id' => 2, 'category' => 'Books', 'name' => 'PHP Basics'],
    ['id' => 3, 'category' => 'Electronics', 'name' => 'Smartphone'],
    ['id' => 4, 'category' => 'Books', 'name' => 'Data Structures']
];

$groupedProducts = group_by_key($products, 'category');
print_r($groupedProducts);

/*
Expected Output:
Array
(
    [Electronics] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [category] => Electronics
                    [name] => Laptop
                )

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

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

            [1] => Array
                (
                    [id] => 4
                    [category] => Books
                    [name] => Data Structures
                )
        )
)
*/
?>
How it works: This function takes an array of associative arrays and groups them into a new associative array where keys are derived from the values of a specified grouping key. Each group contains an array of the original items that share that key's value. This is highly useful for organizing data for display or further processing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs