PHP

Grouping PHP Array Elements by a Specific Key

Efficiently group elements within a PHP array into a new associative array based on the value of a specified key. Ideal for organizing and categorizing data.

<?php
function groupArrayByKey(array $array, string $key):
{
    $grouped = [];
    foreach ($array as $item) {
        if (isset($item[$key])) {
            $grouped[$item[$key]][] = $item;
        } else {
            // Handle items without the specified key, e.g., group them separately or ignore
            $grouped['__ungrouped__'][] = $item;
        }
    }
    return $grouped;
}

$users = [
    ['id' => 1, 'name' => 'Alice', 'role' => 'admin'],
    ['id' => 2, 'name' => 'Bob', 'role' => 'editor'],
    ['id' => 3, 'name' => 'Charlie', 'role' => 'admin'],
    ['id' => 4, 'name' => 'David', 'role' => 'viewer'],
    ['id' => 5, 'name' => 'Eve', 'role' => 'editor'],
    ['id' => 6, 'name' => 'Frank', 'status' => 'active'] // Item without 'role'
];

$groupedByRole = groupArrayByKey($users, 'role');

print_r($groupedByRole);
/* Output:
Array
(
    [admin] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Alice
                    [role] => admin
                )

            [1] => Array
                (
                    [id] => 3
                    [name] => Charlie
                    [role] => admin
                )

        )

    [editor] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [name] => Bob
                    [role] => editor
                )

            [1] => Array
                (
                    [id] => 5
                    [name] => Eve
                    [role] => editor
                )

        )

    [viewer] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [name] => David
                    [role] => viewer
                )

        )

    [__ungrouped__] => Array
        (
            [0] => Array
                (
                    [id] => 6
                    [name] => Frank
                    [status] => active
                )

        )

)
*/
?>
How it works: This snippet provides a reusable function `groupArrayByKey` to organize a flat array of associative arrays into a new array where elements are grouped under keys derived from a specified property. It iterates through the input array, and for each item, it uses the value of the designated key to create a new sub-array (if it doesn't exist) and appends the current item to it. This is highly useful for categorizing data, such as grouping users by their role or products by category, making subsequent processing or display more manageable.

Need help integrating this into your project?

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

Hire DigitalCodeLabs