phparrayslaravelmultidimensional-arraygrouping

Group data from a multidimensional array in Laravel by a deep column value and accumulate values from another column


This is my data:

$dataItems = [
    [
        'id' => 1,
        'serial' => "XXXXXXAA1",
        'pd_item_info' =>
        [
            'id' => 1,
            'quantity' => 5,
            'ipo_item_pml_info' => 
            [
                'id' => 1,
                'product_name' => 'Keyboard'
            ]
        ]
    ], 
    [
        'id' => 2,
        'serial' => "XXXXXXAA2",
        'pd_item_info' =>
        [
            'id' => 2,
            'quantity' => 10,
            'ipo_item_pml_info' => 
            [
                'id' => 2,
                'product_name' => 'Keyboard'
            ]
        ]
    ]
];

and I need to have this output:

$output = [
    'product_name' => "Keyboard",
    'serial' => ["XXXXXXAA1", "XXXXXXAA2"]
];

Using foreach and array_push in Laravel, how can I merge duplicate product_name values and join their serial values?


Solution

  • i assume pd_item_info and ipo_item_pml_info always there

    first distiguish the array key based on product name and all the serial key is append under same product name

    foreach($dataItems as $item) {
        $products[$item['pd_item_info']['ipo_item_pml_info']['product_name']][] = $item['serial'];
    }
    
    //output
    // [
    //     'Keyboard' => ['XXXXXXAA1', 'XXXXXXAA2'];
    // ]
    

    next, formatting according to your needed

    foreach($products as $key => $product) {
        $output[] = [
            'product_name' => $key,
            'serial' => $product
        ];
    }
    

    Thats it.. =D