PHP
Group PHP Array Elements by Common Key Value
Learn to effectively group elements of an associative array based on a shared key's value, creating a structured hierarchical array in PHP.
<?php
$products = [
['id' => 1, 'category' => 'Electronics', 'name' => 'Laptop'],
['id' => 2, 'category' => 'Books', 'name' => 'PHP Guide'],
['id' => 3, 'category' => 'Electronics', 'name' => 'Smartphone'],
['id' => 4, 'category' => 'Books', 'name' => 'Novel'],
['id' => 5, 'category' => 'Electronics', 'name' => 'Tablet'],
];
$groupedProducts = [];
foreach ($products as $product) {
$category = $product['category'];
if (!isset($groupedProducts[$category])) {
$groupedProducts[$category] = [];
}
$groupedProducts[$category][] = $product;
}
print_r($groupedProducts);
// More complex grouping using array_reduce
$groupedByCallback = array_reduce($products, function ($carry, $item) {
$carry[$item['category']][] = $item;
return $carry;
}, []);
print_r($groupedByCallback);
?>
How it works: This snippet demonstrates how to group a list of associative arrays based on the value of a specific key (e.g., 'category'). It iterates through the original array, using the key's value to create new keys in the `$groupedProducts` array. Each new key then contains an array of all elements sharing that value, effectively categorizing your data. The `array_reduce` example shows a functional approach to achieve the same result, offering a compact alternative.