## 按月统计时补全月份并返回格式化数据结构
```
/**
* 按月统计时补全月份并返回格式化数据结构
* @param $start_time 统计范围(开始时间、时间戳)
* @param $end_time 统计范围(结束时间、时间戳)
* @param $arr 待补充数组(数组中必须含有created_at字段),二维数组可以为空
* @return array
*/
function pad_month($start_time,$end_time,$arr){
$start_year = date('Y',$start_time); //2018
$start_month = intval(date('m',$start_time)); //6
$end_year = date('Y',$end_time); //2019
$end_month = intval(date('m',$end_time));//6
$new = [];//用来存放格式化后的新数组
if(!empty($arr)){
foreach ($arr as $v){
$year = date('Y',$v['created_at']);
$month = date('m',$v['created_at']);
$new[$year.$month]['month'] = date('Y-m',$v['created_at']);
$new[$year.$month]['num'] = isset($new[$year.$month]['num']) ? $new[$year.$month]['num']+$v['num'] : 0;
}
}
//判断开始时间和结束时间是否是同一年
if($start_year == $end_year){
for ($i=$start_month;$i<=$end_month;$i++){
$month = str_pad($i,2,0,STR_PAD_LEFT);
if(!array_key_exists($start_year.$month,$new)){
$new[$start_year.$month] = ['month'=>$start_year.'-'.$month,'num'=>0];
}
}
}else{
$diff = $end_year - $start_year + 1;//相差的年数
for ($y=1;$y<=$diff;$y++){
for($i=$start_month;$i<=12;$i++){
$month = str_pad($i,2,0,STR_PAD_LEFT);
if(!array_key_exists($start_year.$month,$new)){
$new[$start_year.$month] = ['month'=>$start_year.'-'.$month,'num'=>0];
}
//如果与结束时间年月相等则结束循环
if($start_year.$i == $end_year.$end_month){
break;
}
}
$start_year++;//年数增加一
$start_month = 1;//重置月份
}
}
ksort($new);
return array_values($new);
}
```