PHP

Group PHP Associative Array by Key Value

Learn to organize a PHP array of associative arrays into logical groups based on the value of a specified key. Ideal for categorizing data efficiently.

function groupByKey(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 put them in a default group
            $grouped['__ungrouped__'][] = $item;
        }
    }
    return $grouped;
}

$products = [
    ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics'],
    ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics'],
    ['id' => 3, 'name' => 'Keyboard', 'category' => 'Peripherals'],
    ['id' => 4, 'name' => 'Monitor', 'category' => 'Electronics'],
];

$groupedByCategory = groupByKey($products, 'category');
/*
$groupedByCategory will be:
[
    'Electronics' => [
        ['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics'],
        ['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics'],
        ['id' => 4, 'name' => 'Monitor', 'category' => 'Electronics'],
    ],
    'Peripherals' => [
        ['id' => 3, 'name' => 'Keyboard', 'category' => 'Peripherals'],
    ]
]
*/
How it works: This snippet demonstrates how to group a list of associative arrays based on the value of a specified key. The `groupByKey` function iterates through the input array, using the value of the designated `$key` as the new outer array key. Each item is then appended to the corresponding group, creating a structured array where related items are easily accessible for further processing or display.

Need help integrating this into your project?

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

Hire DigitalCodeLabs