Skip to content
Advertisement

sum value in foreach loop based on another value php

I have an array like below. There are id, label, cost, and cid in an array. We want to sum the cost based on the cid like for cid 22 cost should be 196.5 and for cid 11 cost should be 44.4. In our out put array we want to keep the label, cost (sum), and cid, Please see expected output array.

Array
(
    [0] => Array
        (
            [id] => 1331
            [label] => PM1
            [cost] => 98.25
            [cid] => 22
            [product_id] => 133
        )

    [1] => Array
        (
            [id] => 1332
            [label] => PM3
            [cost] => 22.20
            [cid] => 11
            [product_id] => 133
        )

    [2] => Array
        (
            [id] => 1341
            [label] => PM1
            [cost] => 98.25
            [cid] => 22
            [product_id] => 134
        )

    [3] => Array
        (
            [id] => 1342
            [label] => PM3
            [cost] => 22.20
            [cid] => 11
            [product_id] => 134
        )

)

Tried below

foreach ($array $key => $value) {

                         $final[$value['cid']] += $value['cost'];
                        } 

                       print_r ($final);

Getting below as an output

Array
(
    [22] => 196.5
    [11] => 44.4
)

Want expected output like below.

Array
    (
        [22] =>  Array
           (
            [label] => PM1
            [cost] => 196.5
            [cid] => 22
           )
        [11] => Array
           (
            [label] => PM3
            [cost] => 44.4
            [cid] => 11
           )
    )

Basically want to sum cost based on cid and want to keep the label, cost (sum), and cid.

Any help will be greatly appreciated.

Advertisement

Answer

$list = [
    [ 'id' => 1331, 'label' => 'PM1', 'cost' => 98.25, 'cid' => 22, 'product_id' => 133 ],
    [ 'id' => 1332, 'label' => 'PM3', 'cost' => 22.20, 'cid' => 11, 'product_id' => 133 ],
    [ 'id' => 1341, 'label' => 'PM1', 'cost' => 98.25, 'cid' => 22, 'product_id' => 134 ],
    [ 'id' => 1342, 'label' => 'PM3', 'cost' => 22.20, 'cid' => 11, 'product_id' => 134 ]
];

$result = [];

array_walk($list, function ($item) use (&$result) {
  if (isset($result[$item['cid']])) {
    $result[$item['cid']]['cost'] = $item['cost'] + $result[$item['cid']]['cost'];
  } else {
    $result[$item['cid']] = [ 'label' => $item['label'], 'cost' => $item['cost'], 'cid' => $item['cid'] ];
  }
});

print_r($result);

Output:

Array
(
    [22] => Array
        (
            [label] => PM1
            [cost] => 196.5
            [cid] => 22
        )

    [11] => Array
        (
            [label] => PM3
            [cost] => 44.4
            [cid] => 11
        )

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