Skip to content
Advertisement

How to sum an associative array in laravel by there keys?

I have an array which will have an SKU number, it can be repeated so want to sum of that SKU qty at once and insert in DB table.

`$data = array(
 0 => array(
 '0' => 'SKU',
 '1' => 'header1',
 '2' => 'header2',
 '3' => 'qty'
),
1 => array(
 '0' => 'SKU-abc',
 '1' => 50,
 '2' => 0,
 '3' => 50
),
2 => array(
'0' => 'SKU-pqr',
'1' => 50,
'2' => 0,
'3' => 50
),
3 => array(
'0' => 'SKU-abc',
'1' => 0,
'2' => 25,
'3' => 25

)`

How can i sum the same sku as index 1 and 3 have and remove the 1st index?

Advertisement

Answer

Using the solution on this Answer

here is how to do it:

$data = array(
 0 => array(
 '0' => 'SKU',
 '1' => 'header1',
 '2' => 'header2',
 '3' => 'qty'
),
1 => array(
 '0' => 'SKU-abc',
 '1' => 50,
 '2' => 0,
 '3' => 50
),
2 => array(
'0' => 'SKU-pqr',
'1' => 50,
'2' => 0,
'3' => 50
),
3 => array(
'0' => 'SKU-abc',
'1' => 0,
'2' => 25,
'3' => 25
));

$res  = array();
foreach($data as $vals){
    if(array_key_exists($vals['0'],$res)){
        $res[$vals['0']]['1']   += $vals['1'];
        $res[$vals['0']]['2']   += $vals['2'];
        $res[$vals['0']]['3']   += $vals['3'];
        $res[$vals['0']]['0']    = $vals['0'];
    }
    else{
        $res[$vals['0']]  = $vals;
    }
}

print_r($res);

The result is:

Array
(
    [SKU] => Array
        (
            [0] => SKU
            [1] => header1
            [2] => header2
            [3] => qty
        )

    [SKU-abc] => Array
        (
            [0] => SKU-abc
            [1] => 50
            [2] => 25
            [3] => 75
        )

    [SKU-pqr] => Array
        (
            [0] => SKU-pqr
            [1] => 50
            [2] => 0
            [3] => 50
        )

)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement