具有相同键的数组的Sum元素

时间:2015-12-15 10:55:00

标签: php arrays php-5.3

我有一个如下所示的对象数组:

[{"SerialNo":"38","Name":"Client X","CounterDate":"2015-12-12","CursUSD":"3.91","M1":"29007","M2":"142109","M3":"403","M4":"383","M5":"171116"},
 {"SerialNo":"38","Name":"Client X","CounterDate":"2015-11-11","CursUSD":"3.85","M1":"26605","M2":"126979","M3":"370","M4":"360","M5":"153584"},
 {"SerialNo":"69","Name":"Client X2","CounterDate":"2015-12-11","CursUSD":"3.90","M1":"6","M2":"7","M3":"8","M4":"9","M5":"10"},
 {"SerialNo":"69","Name":"Client X2","CounterDate":"2015-12-09","CursUSD":"3.88","M1":"1","M2":"2","M3":"3","M4":"4","M5":"5"}
 {"SerialNo":"89","Name":"Client X3","CounterDate":"2015-12-09","CursUSD":"3.88","M1":"1","M2":"2","M3":"3","M4":"4","M5":"5"}]

我尝试组合具有相同SerialNo的子数组。数据几乎总是成对出现。如果没有,它只是一条线,应该保留。 (如客户端X3)

我需要的输出是这样的:

[{"SerialNo":"38","Name":"Client X","CounterDate":"2015-12-12","CursUSD":"3.91","M1":"2402","M2":"15130","M3":"33","M4":"23","M5":"17532"},
 {"SerialNo":"69","Name":"Client X2","CounterDate":"2015-12-11","CursUSD":"3.90","M1":"5","M2":"5","M3":"5","M4":"5","M5":"5"},
 {"SerialNo":"89","Name":"Client X3","CounterDate":"2015-12-09","CursUSD":"3.88","M1":"1","M2":"2","M3":"3","M4":"4","M5":"5"}]

所以保留了SerialNo和Name,CounterDate和CursUSD是第一线遇到的,M1.firstline - M1.secondline,M2.firstline - M2.secondline ...

1 个答案:

答案 0 :(得分:3)

$array = json_decode($json, true);

$result = array_reduce($array, function ($result, $item) {
    if (!isset($result[$item['SerialNo']])) {
        $result[$item['SerialNo']] = $item;
    } else {
        $result[$item['SerialNo']]['M1'] += $item['M1'];
        $result[$item['SerialNo']]['M2'] += $item['M2'];
        $result[$item['SerialNo']]['M3'] += $item['M3'];
        $result[$item['SerialNo']]['M4'] += $item['M4'];
        $result[$item['SerialNo']]['M5'] += $item['M5'];
    }
    return $result;
}, array());

var_dump(json_encode($result));