phparraysmultidimensional-arraygroupingmerging-data

Group rows of data in a multidimensional array by a column and merge subarrays in another column


I am trying to group the data in my 3d array by one column value (order_id) and merge the subarray values in the products column within each group.

Sample data:

$ordersGlobal = [
    [
        "order_id" => "65", 
        "products" => [
           [
              "description" => "Test6", 
              "brand" => "ACL", 
              "code" => "303127005576", 
              "OriginalPrice" => "328.0000"
           ] 
        ] 
    ], 
    [
        "order_id" => "66",  
        "products" => [
            [
                "description" => "Test5", 
                "brand" => "TEA", 
                "code" => "3900055", 
                "OriginalPrice" => "43.0000" 
            ] 
        ] 
    ], 
    [
        "order_id" => "66",
        "products" => [
            [
                "description" => "Te3st4", 
                "brand" => "TEA", 
                "code" => "3900056", 
                "OriginalPrice" => "43.0000"
            ] 
        ] 
    ]
] 

Desired result:

[
    [
        "order_id" => "65", 
        "products" => [
           [
              "description" => "Test6", 
              "brand" => "ACL", 
              "code" => "303127005576", 
              "OriginalPrice" => "328.0000"
           ] 
        ] 
    ], 
    [
        "order_id" => "66",  
        "products" => [
            [
                "description" => "Test5", 
                "brand" => "TEA", 
                "code" => "3900055", 
                "OriginalPrice" => "43.0000" 
            ],
            [
                "description" => "Te3st4", 
                "brand" => "TEA", 
                "code" => "3900056", 
                "OriginalPrice" => "43.0000"
            ] 

        ] 
    ]
]

My coding attempt:

$order_merge = array();
foreach ($ordersGlobal as $k => $data) {
    $orderId1 = $data['order_id'];
    $orderId2 = next($ordersGlobal)['order_id'] ?? false;
    if ($orderId1 == $orderId2) {
        $order_merge[$k]['order_id'] = $data['order_id'];
        $order_merge[$k]['products'] = array_merge(
            next($ordersGlobal)['products'],
            $data['products']
        );
    } else {
        $order_merge[$k]['order_id'] = $data['order_id'];
        // $order_merge[$k]['customerId'] = 1 $order_merge[$k]['products'] = $data['products'];
    }
} 

Solution

  • I think it should works

    $productsTemp = [];
    $ordersMerge = [];
    
    foreach ($ordersGlobal as $actualOrder)
    {
        if (key_exists($actualOrder["order_id"], $productsTemp))
        {
            array_push($productsTemp[$actualOrder["order_id"]]["products"], $actualOrder["products"][0]);
        }
        else
        {
            $productsTemp[$actualOrder["order_id"]]["products"] = $actualOrder["products"];
        }
    }
    
    $ordersMerge[] = $productsTemp;