PHP

Group Array Elements by Specific Key

Learn to group an array of associative arrays by a common key's value, transforming flat data into a structured, grouped format.

<?php
$users = [
    ['id' => 1, 'name' => 'Alice', 'city' => 'New York'],
    ['id' => 2, 'name' => 'Bob', 'city' => 'Los Angeles'],
    ['id' => 3, 'name' => 'Charlie', 'city' => 'New York'],
    ['id' => 4, 'name' => 'David', 'city' => 'Chicago'],
    ['id' => 5, 'name' => 'Eve', 'city' => 'Los Angeles'],
];

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

$users_by_city = group_by_key($users, 'city');
// print_r($users_by_city);
/*
Expected output:
Array
(
    [New York] => Array
        (
            [0] => Array
                (
                    [id] => 1
                    [name] => Alice
                    [city] => New York
                )

            [1] => Array
                (
                    [id] => 3
                    [name] => Charlie
                    [city] => New York
                )

        )

    [Los Angeles] => Array
        (
            [0] => Array
                (
                    [id] => 2
                    [name] => Bob
                    [city] => Los Angeles
                )

            [1] => Array
                (
                    [id] => 5
                    [name] => Eve
                    [city] => Los Angeles
                )

        )

    [Chicago] => Array
        (
            [0] => Array
                (
                    [id] => 4
                    [name] => David
                    [city] => Chicago
                )

        )

)
*/
?>
How it works: This snippet provides a flexible function, `group_by_key`, to organize an array of associative arrays based on a specified key's value. It iterates through the input array, using the value of the chosen key (e.g., 'city') to create new top-level keys in the result. Each group then contains all original array elements that share that common key value, effectively transforming a flat list into a structured, categorized dataset.

Need help integrating this into your project?

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

Hire DigitalCodeLabs