PHP
Group Array of Associative Arrays by Key
Learn how to efficiently group a list of associative arrays into a new array, where items are categorized by the value of a specified key, useful for organizing data.
<?php
function group_by_key(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, if necessary
// For this example, they will be ignored or grouped under a default key.
// You might add them to a 'null' or 'unassigned' key
// $grouped['unassigned'][] = $item;
}
}
return $grouped;
}
$products = [
['id' => 1, 'name' => 'Laptop', 'category' => 'Electronics', 'price' => 1200],
['id' => 2, 'name' => 'Smartphone', 'category' => 'Electronics', 'price' => 800],
['id' => 3, 'name' => 'T-Shirt', 'category' => 'Apparel', 'price' => 25],
['id' => 4, 'name' => 'Jeans', 'category' => 'Apparel', 'price' => 60],
['id' => 5, 'name' => 'Monitor', 'category' => 'Electronics', 'price' => 300]
];
$groupedByCategory = group_by_key($products, 'category');
// var_dump($groupedByCategory);
/* Expected Output (simplified):
[
"Electronics" => [
["id" => 1, ...],
["id" => 2, ...],
["id" => 5, ...]
],
"Apparel" => [
["id" => 3, ...],
["id" => 4, ...]
]
]
*/
?>
How it works: This snippet defines a `group_by_key` function that takes an array of associative arrays and a key name. It iterates through each sub-array, using the value of the specified key as the new top-level key in the result array. Each item matching that key is then added as an element to the corresponding sub-array, effectively categorizing and organizing your data.