根据开始时间,结束时间,转化成连续的小时,天,周等

function bmCalTimeSection($pdStartTime, $pdEndTime, $psGranularity) {
$tdYear = date('Y', $pdStartTime);
$tdMonth = date('m', $pdStartTime);
$tdDate = date('d', $pdStartTime);
$tdHour = date('H', $pdStartTime);

$tdDay = date('w', $pdStartTime); // 周日开始
if ($tdDay < 0) $tdDay = 6;

$taResult = array();
if ($psGranularity == "Hour") {
$tdNow = mktime($tdHour,0,0, $tdMonth,$tdDate,$tdYear);
while($tdNow <= strtotime("+1 Hour",$pdEndTime)) {
$taResult[] = array('time'=>$tdNow, 'title'=>date('H', $tdNow));
$tdHour++;
$tdNow = mktime($tdHour,0,0, $tdMonth,$tdDate,$tdYear);
}
}
elseif ($psGranularity == "Day") {
$tdNow = mktime(0,0,0, $tdMonth,$tdDate,$tdYear);
while($tdNow <=strtotime("+0 Day",$pdEndTime)) {
$taResult[] = array('time'=>$tdNow, 'title'=>date('Y-m-d', $tdNow));
$tdDate++;
$tdNow = mktime(0,0,0, $tdMonth,$tdDate,$tdYear);
}
}
elseif ($psGranularity == "Week") {
$tdDate -= $tdDay;
$tdNow = mktime($tdHour,0,0, $tdMonth,$tdDate,$tdYear);
while($tdNow <strtotime("+0 Week",$pdEndTime)) {
$taResult[] = array('time'=>$tdNow, 'title'=>date('m-d', $tdNow));
$tdDate += 7;
$tdNow = mktime(0,0,0, $tdMonth,$tdDate,$tdYear);
}
}
elseif ($psGranularity == "Month") {
$tdNow = mktime(0,0,0, $tdMonth,1,$tdYear);
while($tdNow <= strtotime("+0 Month",$pdEndTime)) {
$taResult[] = array('time'=>$tdNow, 'title'=>date('Y-m', $tdNow));
$tdMonth++;
$tdNow = mktime(0,0,0, $tdMonth,1,$tdYear);
}
}
elseif ($psGranularity == "Year") {
$tdNow = mktime(0,0,0, 1,1,$tdYear);
while($tdNow < strtotime("+0 Year",$pdEndTime)) {
$taResult[] = array('time'=>$tdNow, 'title'=>date('Y', $tdNow));
$tdYear++;
$tdNow = mktime(0,0,0, 1,1,$tdYear);
}
}

return $taResult;
}

 

使用方法:

$start=strtotime('2018-05-01');
$end=strtotime('2018-05-08');
$res=bmCalTimeSection($start,$end,'Hour');

日期作为数组的键值

$data=array{

["a_res"]=>
  array(3) {
  [0]=>
  array(3) {
  ["a_num"]=>
  int(10)
  ["a_user_num"]=>
  int(15)
  ["date"]=>
  string(10) "2018-02-09"
  }

}

 

$func_arr=function($params) use ($data){
$one_arr=[];
foreach($data[$params] as $val){
$one_arr[$val['date']]=$val;
}
return $one_arr;
};
$a_data=$func_arr('a_res');//使用
$b_data=$func_arr('b_res');
$c_data=$func_arr('c_res');

//$time为连续的时间,该天有数据则就是之,没有补0
foreach($time as $k=>$v){
$res_array[$k]['time']=$v['title'];
$res_array[$k]['a_user_num']=$a_data[$v['title']]['a_user_num']?$a_data[$v['title']]['a_user_num']:0;
$res_array[$k]['b_user_num']=$b_data[$v['title']]['b_user_num']?$b_data[$v['title']]['b_user_num']:0;
$res_array[$k]['c_user_num']=$c_data[$v['title']]['c_user_num']?$c_data[$v['title']]['c_user_num']:0;
$res_array[$k]['total_user_num']=$a_data[$v['title']]['a_user_num']+$b_data[$v['title']]['b_user_num']+$c_data[$v['title']]['c_user_num'];

}

 

posted on 2018-05-08 11:32  阳雪凌空  阅读(198)  评论(0编辑  收藏  举报

导航