PHP
Group Array Elements by Key
Transform a flat list of associative arrays into a structured, grouped array where elements are organized by a common key's value in PHP.
<?php
function groupArrayBy(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, e.g., put them in a '__misc__' group
$grouped['__misc__'][] = $item;
}
}
return $grouped;
}
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics'],
['id' => 2, 'name' => 'Keyboard', 'category' => 'Electronics'],
['id' => 3, 'name' => 'Table', 'category' => 'Furniture'],
['id' => 4, 'name' => 'Mouse', 'category' => 'Electronics'],
['id' => 5, 'name' => 'Chair', 'category' => 'Furniture'],
];
$groupedProducts = groupArrayBy($products, 'category');
// print_r($groupedProducts);
/*
Array
(
[Electronics] => Array
(
[0] => Array
(
[id] => 1
[name] => Laptop
[category] => Electronics
)
[1] => Array
(
[id] => 2
[name] => Keyboard
[category] => Electronics
)
[2] => Array
(
[id] => 4
[name] => Mouse
[category] => Electronics
)
)
[Furniture] => Array
(
[0] => Array
(
[id] => 3
[name] => Table
[category] => Furniture
)
[1] => Array
(
[id] => 5
[name] => Chair
[category] => Furniture
)
)
)
*/
How it works: This `groupArrayBy` function takes a flat array of associative arrays and groups them into a new associative array. The keys of the new array are the values of the specified `$key` from the original items, and each value is an array containing all the items that share that key's value. This is highly useful for organizing data by categories or any common attribute.