PHP

Group Associative PHP Arrays by a Key

Efficiently organize a list of associative arrays into groups based on the value of a specified common key, simplifying data categorization.

function group_by_key(array $array, string $key): array
{
    $grouped = [];
    foreach ($array as $item) {
        if (isset($item[$key])) {
            $grouped[$item[$key]][] = $item;
        } else {
            // Handle items without the grouping key, or ignore them
            $grouped['__ungrouped__'][] = $item;
        }
    }
    return $grouped;
}

$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', 'category' => 'Books'],
];

$groupedProducts = group_by_key($products, 'category');
/* Expected:
[
    'Electronics' => [
        ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics'],
        ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics'],
        ['id' => 4, 'name' => 'Keyboard', 'category' => 'Electronics'],
    ],
    'Books' => [
        ['id' => 3, 'name' => 'Book', 'category' => 'Books'],
        ['id' => 5, 'name' => 'Magazine', 'category' => 'Books'],
    ],
]
*/
print_r($groupedProducts);
How it works: This function groups an array of associative arrays based on the value of a specified key. It iterates through the input array, using the value of the grouping key as the new top-level key in the result array, and appends the original item to the corresponding group.

Need help integrating this into your project?

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

Hire DigitalCodeLabs