PHP
Group PHP Array Items by a Key
Learn an efficient way to organize and group elements within an array of associative arrays based on the value of a specific key, creating structured data.
<?php
$data = [
['id' => 1, 'category' => 'fruits', 'item' => 'apple'],
['id' => 2, 'category' => 'vegetables', 'item' => 'carrot'],
['id' => 3, 'category' => 'fruits', 'item' => 'banana'],
['id' => 4, 'category' => 'dairy', 'item' => 'milk'],
['id' => 5, 'category' => 'vegetables', 'item' => 'broccoli']
];
$groupedData = [];
foreach ($data as $item) {
$category = $item['category'];
if (!isset($groupedData[$category])) {
$groupedData[$category] = [];
}
$groupedData[$category][] = $item;
}
echo "<pre>";
print_r($groupedData);
echo "</pre>";
/*
Output will be:
Array
(
[fruits] => Array
(
[0] => Array
(
[id] => 1
[category] => fruits
[item] => apple
)
[1] => Array
(
[id] => 3
[category] => fruits
[item] => banana
)
)
[vegetables] => Array
(
[0] => Array
(
[id] => 2
[category] => vegetables
[item] => carrot
)
[1] => Array
(
[id] => 5
[category] => vegetables
[item] => broccoli
)
)
[dairy] => Array
(
[0] => Array
(
[id] => 4
[category] => dairy
[item] => milk
)
)
)
*/
?>
How it works: This snippet demonstrates how to transform a flat list of associative arrays into a nested structure where items are grouped by the value of a specified key (in this case, 'category'). It iterates through the original array, and for each item, it checks if a corresponding key exists in the new `$groupedData` array. If not, it initializes an empty array for that key before adding the current item to it. This is a fundamental pattern for organizing and processing data.