PHP
Grouping Array Elements by a Common Key
Efficiently group an array of associative arrays or objects by a specified key's value in PHP, transforming flat data into a structured hierarchy for easier processing and analysis.
<?php
function groupArrayByKey(array $array, string $key): array
{
$grouped = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$grouped[$item[$key]][] = $item;
} else {
// Optionally handle items without the key
// $grouped['__ungrouped__'][] = $item;
}
}
return $grouped;
}
$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' => 'Cookbook']
];
$groupedProducts = groupArrayByKey($products, 'category');
print_r($groupedProducts);
/*
Output:
Array
(
[Electronics] => Array
(
[0] => Array
(
[id] => 1
[category] => Electronics
[name] => Laptop
)
[1] => Array
(
[id] => 3
[category] => Electronics
[name] => Smartphone
)
)
[Books] => Array
(
[0] => Array
(
[id] => 2
[category] => Books
[name] => PHP Guide
)
[1] => Array
(
[id] => 4
[category] => Books
[name] => Cookbook
)
)
)
*/
?>
How it works: This snippet provides a reusable function `groupArrayByKey` that takes an array of associative arrays (or objects treatable as such) and a key name. It iterates through the input array, using the value of the specified key from each item as the new key for the grouped array. Each item is then appended to the array associated with its respective group key, effectively organizing the data into a hierarchical structure.