PHP

Group Associative Arrays by Key in PHP

Efficiently organize an array of associative arrays into a new structure where elements are grouped based on the common value of a specified key.

function groupArrayByKey(array $array, string $key): array {
    $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
            $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']
];

$usersByRole = groupArrayByKey($users, 'role');
print_r($usersByRole);
/* Expected 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 )
        )
    [viewer] => Array
        (
            [0] => Array ( [id] => 4 [name] => David [role] => viewer )
        )
)*/
How it works: The `groupArrayByKey` function takes an array of associative arrays and a key name. It iterates through each item, using the value of the specified key as the new top-level key in the `$grouped` array. Each group then contains an array of the original items that share that key value. This is highly useful for categorizing data fetched from databases or APIs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs