PHP
Group Associative Array Elements by Key
Learn a common pattern for organizing data by grouping elements from an array of associative arrays based on a shared key's value, transforming flat data into nested structures.
<?php
$orders = [
['order_id' => 101, 'customer_id' => 1, 'item' => 'Laptop', 'price' => 1200],
['order_id' => 102, 'customer_id' => 2, 'item' => 'Mouse', 'price' => 25],
['order_id' => 103, 'customer_id' => 1, 'item' => 'Keyboard', 'price' => 75],
['order_id' => 104, 'customer_id' => 3, 'item' => 'Monitor', 'price' => 300],
['order_id' => 105, 'customer_id' => 2, 'item' => 'Webcam', 'price' => 50],
];
$groupedOrders = [];
foreach ($orders as $order) {
$customerId = $order['customer_id'];
if (!isset($groupedOrders[$customerId])) {
$groupedOrders[$customerId] = [];
}
$groupedOrders[$customerId][] = $order;
}
echo "Orders grouped by Customer ID:
";
print_r($groupedOrders);
?>
How it works: This snippet demonstrates how to group a flat list of associative arrays into a nested structure based on a common key. It iterates through the `$orders` array, using the `customer_id` as the key for the new `$groupedOrders` array. Each `customer_id` becomes a key, and its value is an array containing all orders associated with that customer. This is a fundamental technique for organizing and displaying related data, such as showing all orders for each customer.