求和陣列:
$data = array(
'0' => array
(
'id' => 1518,
'date' => 1495728000,
'type' => 61,
'content' => '{"2":2,"3":4,"4":6,"5":8}'
),
'1' => array
(
'id' => 1519,
'date' => 1495641600,
'type' => 62,
'content' => '{"1":3,"3":5,"2":5,"6":6}'
),
'2' => array
(
'id' => 1519,
'date' => 1495555200,
'type' => 63,
'content' => '{"7":219,"8":112,"9":268}'
),
'3' => array
(
'id' => 1519,
'date' => 1495468800,
'type' => 64,
'content' => '{"14":219,"16":112,"23":268,"18":268}'
)
);
/**求和函式
*$n 求和天數
*$data 求和資料
*/
function sum($n,$data)
{
$sum = $sum_tmp = array();
foreach ($data as $key => $val) {
// print_r($val);exit;
$content = json_decode($val['content'],true);
// print_r($content);exit;
if ((($key + 1) % $n) != 0) {
//非$n的倍數 一直累加
foreach($content as $k=>$v){
if(!isset($sum_tmp[$k])){
$sum_tmp[$k] = $v;
}else{
$sum_tmp[$k] += $v;
}
}
if (($key + 1) == count($data)) {
$sum[$val['date']]['date'] = date('Y-m-d',($val['date']+($n-1)*86400)).'---'.date('Y-m-d',$val['date']);
foreach($sum_tmp as $k=>$v){
$sum[$val['date']][$k] = $v;
}
}
} elseif ((($key + 1) % $n) == 0) {
//$n的倍數 縫$n求和
foreach($content as $k=>$v){
if(!isset($sum_tmp[$k])){
$sum_tmp[$k] = $v;
}else{
$sum_tmp[$k] += $v;
}
}
$sum[$val['date']]['date'] = date('Y-m-d',($val['date']+($n-1)*86400)).'--'.date('Y-m-d',$val['date']);
foreach($sum_tmp as $k=>$v){
$sum[$val['date']][$k] = $v;
}
unset($sum_tmp);
}
}
return $sum;
}
print_r(sum(2,$data)); //注紅色部分為解決求和陣列之間單元數量不等的問題
列印結果為:
Array
(
[1495641600] => Array
(
[date] => 2017-05-26--2017-05-25
[2] => 7
[3] => 9
[4] => 6
[5] => 8
[1] => 3
[6] => 6
)
[1495468800] => Array
(
[date] => 2017-05-24--2017-05-23
[7] => 219
[8] => 112
[9] => 268
[14] => 219
[16] => 112
[23] => 268
[18] => 268
)
)