[{"month":"2021-01-01","kpi":"3238"},{"month":"2021-02-01","kpi":"2726"},{"month":"2021-02-08","kpi":"2159"},{"month":"2021-03-01","kpi":"3026"},{"month":"2021-03-04","kpi":"1"},{"month":"2021-03-05","kpi":"2"},{"month":"2021-04-01","kpi":"2936"},{"month":"2021-05-01","kpi":"3118"},{"month":"2021-06-01","kpi":"3433"},{"month":"2021-07-01","kpi":"4163"},{"month":"2021-08-01","kpi":"4364"},{"month":"2021-09-01","kpi":"4520"},{"month":"2021-10-01","kpi":"5238"},{"month":"2021-11-01","kpi":"5554"},{"month":"2021-12-01","kpi":"5573"}]
需要把相同月份合并(已经按顺序排了),累加kpi,得到如下结果:
[{"month":"2021-01","kpi":"3238"},{"month":"2021-02","kpi":4885},{"month":"2021-03","kpi":3029},{"month":"2021-04","kpi":"2936"},{"month":"2021-05","kpi":"3118"},{"month":"2021-06","kpi":"3433"},{"month":"2021-07","kpi":"4163"},{"month":"2021-08","kpi":"4364"},{"month":"2021-09","kpi":"4520"},{"month":"2021-10","kpi":"5238"},{"month":"2021-11","kpi":"5554"},{"month":"2021-12","kpi":"5573"}]
private static function mergeDupMonth($kpiList) {
// merge
$n = count($kpiList);
$ans = array();
$thisMonth = substr($kpiList[0]['month'], 0, 7);
$ans[0] = array(
'month' => $thisMonth,
'kpi' => $kpiList[0]['kpi'],
);
$j = 0;
for ($i = 1; $i < $n; $i += 1) {
$lastMonth = $thisMonth;
$thisMonth = substr($kpiList[$i]['month'], 0, 7);
if (strncmp($thisMonth, $lastMonth, 7) == 0) {
$ans[$j]['kpi'] += $kpiList[$i]['kpi'];
} else {
$j += 1;
$ans[$j] = array(
'month' => $thisMonth,
'kpi' => $kpiList[$i]['kpi'],
);
}
}
return $ans;
}
类似implode函数的实现,先处理第0个,再循环后面的
排序 usort($a, function($a, $b) { /* ... */});