PHP

Grouping Associative Array Elements by a Key

Organize and group elements of a PHP associative array based on a common key's value, creating nested arrays for structured data categorization.

$orders = [
    ['order_id' => 101, 'customer_id' => 1, 'amount' => 150.00],
    ['order_id' => 102, 'customer_id' => 2, 'amount' => 200.00],
    ['order_id' => 103, 'customer_id' => 1, 'amount' => 50.00],
    ['order_id' => 104, 'customer_id' => 3, 'amount' => 300.00],
];

$groupedOrders = [];
foreach ($orders as $order) {
    $customerId = $order['customer_id'];
    if (!isset($groupedOrders[$customerId])) {
        $groupedOrders[$customerId] = [];
    }
    $groupedOrders[$customerId][] = $order;
}

print_r($groupedOrders);
/* Expected Output:
Array
(
    [1] => Array
        (
            [0] => Array ( [order_id] => 101 [customer_id] => 1 [amount] => 150 )
            [1] => Array ( [order_id] => 103 [customer_id] => 1 [amount] => 50 )
        )
    [2] => Array
        (
            [0] => Array ( [order_id] => 102 [customer_id] => 2 [amount] => 200 )
        )
    [3] => Array
        (
            [0] => Array ( [order_id] => 104 [customer_id] => 3 [amount] => 300 )
        )
)
*/
How it works: This snippet iterates through a list of `$orders`. For each order, it uses the `customer_id` as a key to create or access a sub-array within `$groupedOrders`. It then appends the current order to that customer's list, effectively grouping all orders by their respective customer IDs. This is a common pattern for organizing relational data.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs