PHP
Group Associative Arrays by a Specific Key
Efficiently organize a flat list of associative arrays into a nested structure, grouping items by a shared key like a category or ID for better data organization.
function groupByKey(array $array, string $key): array {
$grouped = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$grouped[$item[$key]][] = $item;
}
}
return $grouped;
}
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
['id' => 2, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 25],
['id' => 3, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
['id' => 4, 'name' => 'T-Shirt', 'category' => 'Apparel', 'price' => 20],
['id' => 5, 'name' => 'Jeans', 'category' => 'Apparel', 'price' => 60]
];
$groupedProducts = groupByKey($products, 'category');
print_r($groupedProducts);
How it works: The `groupByKey` function takes an array of associative arrays and a string representing the key to group by. It iterates through each item, using the value of the specified key as the new top-level key in the result array. All items sharing the same key value are collected into a sub-array under that key, effectively transforming a flat list into a structured, grouped array.