PHP
Group Associative Arrays by a Shared Key
Learn how to group elements in an array of associative arrays by a common key, creating a nested structure for better data organization and access.
<?php
$items = [
['category' => 'Electronics', 'name' => 'Laptop'],
['category' => 'Books', 'name' => 'PHP Basics'],
['category' => 'Electronics', 'name' => 'Smartphone'],
['category' => 'Books', 'name' => 'JavaScript Guide'],
['category' => 'Home', 'name' => 'Desk Lamp'],
];
$groupedItems = [];
foreach ($items as $item) {
$category = $item['category'];
if (!isset($groupedItems[$category])) {
$groupedItems[$category] = [];
}
$groupedItems[$category][] = $item;
}
print_r($groupedItems);
?>
How it works: This snippet demonstrates how to group an array of associative arrays based on the value of a specific key (e.g., 'category'). It iterates through the original array and organizes items into a new associative array where keys represent the grouping criteria. Each group then contains a sub-array of all items belonging to that category, making data aggregation and display much simpler.