PHP
Group an Array of Associative Arrays by a Common Key
Discover a clean and efficient method to group an array of associative arrays by a specific key, creating structured collections of related data in PHP.
<?php
function groupArrayByKey(array $array, string $key): array
{
$groupedArray = [];
foreach ($array as $item) {
if (isset($item[$key])) {
$groupedArray[$item[$key]][] = $item;
} else {
// Handle items without the specified key, e.g., group them under a 'null' or 'other' key
$groupedArray['other'][] = $item;
}
}
return $groupedArray;
}
$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 = groupArrayByKey($products, 'category');
print_r($groupedProducts);
/* Expected Output:
Array
(
[Electronics] => Array
(
[0] => Array
(
[id] => 1
[name] => Laptop
[category] => Electronics
[price] => 1200
)
[1] => Array
(
[id] => 2
[name] => Mouse
[category] => Electronics
[price] => 25
)
[2] => Array
(
[id] => 3
[name] => Keyboard
[category] => Electronics
[price] => 75
)
)
[Apparel] => Array
(
[0] => Array
(
[id] => 4
[name] => T-Shirt
[category] => Apparel
[price] => 20
)
[1] => Array
(
[id] => 5
[name] => Jeans
[category] => Apparel
[price] => 60
)
)
)
*/
How it works: This function `groupArrayByKey` takes an array of associative arrays and a key name. It iterates through each item, using the value of the specified key from the item as the new outer array's key. Each item that shares the same value for the grouping key is then collected into an array under that key. This is incredibly useful for structuring data for display, reporting, or further processing based on common attributes.