求和数组: $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 ) )
二维数组求和,,,针对键名数量不等的情况
最新推荐文章于 2020-09-28 11:45:23 发布