-3

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?

2
  • Its not really clear what you are asking, its best to assume we cannot read your mind and we are not looking over your shoulder. Explain specifically, with examples or even diagrams where necessary Commented Mar 10, 2022 at 18:36
  • You can check the answer on this question: Link Commented Mar 10, 2022 at 19:39

1 Answer 1

-1

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
        )

)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.