PHP
Group Array Elements by a Specific Key
Efficiently organize and group an array of associative arrays based on the value of a common key, creating a nested structure in PHP for better data management.
<?php
function groupArrayByKey(array $array, string $key): array
{
$grouped = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$grouped[$item[$key]][] = $item;
} else {
// Handle items without the specified key, or add to a 'misc' group
$grouped['__ungrouped__'][] = $item;
}
}
return $grouped;
}
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
['id' => 2, 'name' => 'Keyboard', 'category' => 'Electronics', 'price' => 75],
['id' => 3, 'name' => 'Chair', 'category' => 'Furniture', 'price' => 300],
['id' => 4, 'name' => 'Desk', 'category' => 'Furniture', 'price' => 450],
['id' => 5, 'name' => 'Mouse', 'category' => 'Electronics', 'price' => 30]
];
$groupedProducts = groupArrayByKey($products, 'category');
print_r($groupedProducts);
/* Output:
Array
(
[Electronics] => Array
(
[0] => Array
(
[id] => 1
[name] => Laptop
[category] => Electronics
[price] => 1200
)
[1] => Array
(
[id] => 2
[name] => Keyboard
[category] => Electronics
[price] => 75
)
[2] => Array
(
[id] => 5
[name] => Mouse
[category] => Electronics
[price] => 30
)
)
[Furniture] => Array
(
[0] => Array
(
[id] => 3
[name] => Chair
[category] => Furniture
[price] => 300
)
[1] => Array
(
[id] => 4
[name] => Desk
[category] => Furniture
[price] => 450
)
)
)
*/
How it works: This snippet defines a reusable function `groupArrayByKey` that takes an array of associative arrays and a key string. It iterates through each item, using the value of the specified key as the new top-level key in the `grouped` array. Each item is then appended to an array under its respective group key. This is highly useful for organizing data fetched from a database or API, making it easier to display or process items by category, user, or any other common attribute.