PHP
Group Associative Array Elements by a Common Key
Learn a practical PHP method to group elements of an array of associative arrays based on the value of a specific key, organizing your data for easier access.
<?php
$products = [
['id' => 1, 'category' => 'Electronics', 'name' => 'Laptop'],
['id' => 2, 'category' => 'Books', 'name' => 'PHP Basics'],
['id' => 3, 'category' => 'Electronics', 'name' => 'Smartphone'],
['id' => 4, 'category' => 'Books', 'name' => 'Advanced SQL'],
['id' => 5, 'category' => 'Electronics', 'name' => 'Monitor'],
];
$groupedProducts = [];
foreach ($products as $product) {
$category = $product['category'];
if (!isset($groupedProducts[$category])) {
$groupedProducts[$category] = [];
}
$groupedProducts[$category][] = $product;
}
print_r($groupedProducts);
/* Expected Output:
Array
(
[Electronics] => Array
(
[0] => Array ( [id] => 1 [category] => Electronics [name] => Laptop )
[1] => Array ( [id] => 3 [category] => Electronics [name] => Smartphone )
[2] => Array ( [id] => 5 [category] => Electronics [name] => Monitor )
)
[Books] => Array
(
[0] => Array ( [id] => 2 [category] => Books [name] => PHP Basics )
[1] => Array ( [id] => 4 [category] => Books [name] => Advanced SQL )
)
)
*/
// Alternative using array_reduce for a more functional approach (PHP 7.4+ for arrow functions):
$groupedProductsReduce = array_reduce($products, fn($carry, $item) => (
$carry[$item['category']][] = $item, $carry
), []);
print_r($groupedProductsReduce);
?>
How it works: This snippet demonstrates how to transform a flat list of associative arrays into a grouped structure, where a common key's value becomes the new top-level key. This is a fundamental data transformation technique, often used when displaying lists of items categorized by a specific attribute. The `foreach` loop provides a clear, imperative approach, while `array_reduce` offers a more concise, functional programming style for the same result, especially with PHP 7.4+ arrow functions.