PHP

PHP Group Array by Key

Learn to group elements of a PHP array into sub-arrays based on a common key's value, ideal for categorizing data for reports or UI.

function group_array_by_key(array $array, string $key): array
{
    $grouped = [];
    foreach ($array as $item) {
        if (isset($item[$key])) {
            $grouped[$item[$key]][] = $item;
        } else {
            // Optional: Handle items that don't have the key, e.g., put them in a special group
            $grouped['__ungrouped__'][] = $item;
        }
    }
    return $grouped;
}

// Example usage:
$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics'],
    ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics'],
    ['id' => 3, 'name' => 'Book', 'category' => 'Books'],
    ['id' => 4, 'name' => 'Keyboard', 'category' => 'Electronics'],
    ['id' => 5, 'name' => 'Magazine'] // Item without category
];

$groupedProducts = group_array_by_key($products, 'category');
print_r($groupedProducts);
/* Expected Output:
Array
(
    [Electronics] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Laptop
                    [category] => Electronics
                )
            [1] => Array
                (
                    [id] => 2
                    [name] => Mouse
                    [category] => Electronics
                )
            [2] => Array
                (
                    [id] => 4
                    [name] => Keyboard
                    [category] => Electronics
                )
        )
    [Books] => Array
        (
            [0] => Array
                (
                    [id] => 3
                    [name] => Book
                    [category] => Books
                )
        )
    [__ungrouped__] => Array
        (
            [0] => Array
                (
                    [id] => 5
                    [name] => Magazine
                )
        )
)*/
How it works: The `group_array_by_key` function reorganizes a flat list of associative arrays into a new associative array where keys represent the values of a specified key in the original items, and the values are arrays containing all items that share that key's value. This is extremely useful for categorizing, preparing data for display (e.g., grouped lists), or performing aggregations on subsets of data.

Need help integrating this into your project?

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

Hire DigitalCodeLabs