php array find duplicates, sum them up & delete duplicates

后端 未结 4 1127
无人共我
无人共我 2020-12-01 20:23

i have an array:

Array 
(
[0] => Array
    (
        [setid] => 2
        [income] => 100
    )

[1] => Array
    (
        [setid] => 2
              


        
4条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 20:30

    Just create a new array which you make fast adressable by using the setid as key. And reindex the array at the end.

    $result = array();
    foreach ($array as $val) {
        if (!isset($result[$val['setid']]))
            $result[$val['setid']] = $val;
        else
            $result[$val['setid']]['income'] += $val['income'];
    }
    $result = array_values($result); // reindex array
    

提交回复
热议问题