直接看代码:
/**
* 处理周数据
* @param $data 数据(数据中要有一个时间)
* @return Array
*/
function getWeekData( $data , $start_time , $end_time ) {
$week = $this->getWeekDate( $start_time , $end_time );
# 返回数据
$res = [];
for ( $i = 0; $i < count( $week ); $i++ ) {
$count = 0;
foreach ( $data as $k => $v ) {
if( $v['add_time'] >= $week[$i]['start'] && $v['add_time'] <= $week[$i]['end'] ) {
$count++;
}
}
if( $count ) {
$res[] = [
'day' => '第'. ( $i+1 ) .'周' ,
'start_time' => date( 'Y-m-d' , $week[$i]['start'] ) ,
'end_time' => date( 'Y-m-d' ,$week[$i]['end'] )
];
} else {
$res[] = [
'day' => '第'.( $i+1 ).'周' ,
'start_time' => date( 'Y-m-d' ,$week[$i]['start'] ) ,
'end_time' => date( 'Y-m-d' ,$week[$i]['end'] )
];
}
}
return $res;
}
/**
* 处理周日期
* @param $start_time 开始时间
* @param $end_time 结束时间
* @return Array 每周的开始和结束时间戳
*/
function getWeekDate( $start_time , $end_time ) {
# 每周开始结束时间
$week = [];
# 还有几天这周结束
$add = 0;
switch ( date("w",$start_time) ) {
case 1:
$add = 6;
break;
case 2:
$add = 5;
break;
case 3:
$add = 4;
break;
case 4:
$add = 3;
break;
case 5:
$add = 2;
break;
case 6:
$add = 1;
break;
case 0:
$add = 0;
break;
}
# 本周开始时间
$week_start = mktime(0,0,0,date('m' , $start_time ), 1 ,date('Y' , $start_time ) );
# 本周结束时间
$week_end = mktime( 23 , 59 , 59 , date( 'm' , $start_time ) , date( 'd' , $start_time ) + $add , date( 'y' , $start_time ) );
# 取到第一周的开始结束时间戳
$week[] = [ 'start' => $week_start , 'end' => $week_end ];
# 结束时间前面有几天
$del = 0;
switch ( date( 'w' , $end_time ) ) {
case 1:
$del = 0;
break;
case 2:
$del = 1;
break;
case 3:
$del = 2;
break;
case 4:
$del = 3;
break;
case 5:
$del = 4;
break;
case 6:
$del = 5;
break;
case 0:
$del = 6;
break;
}
# 最后一周开始时间
$last_start = mktime( 0 , 0 , 0 , date( 'm' , $end_time ) , date( 'd' , $end_time ) - $del , date( 'Y' , $end_time ) );
# 最后一周结束时间
$last_end = mktime( 23 , 0 , 0 , date( 'm' , $end_time ) , date( 'd' , $end_time ) , date( 'Y' , $end_time ) );
$last = [ 'start' => $last_start , 'end' => $last_end ];
# 计算中间几个周共多少天
$days_count = round(( $last_start - ( $week_end +1 ) ) / 86400 );
# 第二周开始时间戳
$start_two = $week_end+1;
# 生成中间的几个周的开始结束时间戳
for ( $i = 0; $i < $days_count; $i = $i+7 ) {
$center_start = mktime( 0 , 0 , 0 , date( 'm' , $start_two ) , date( 'd' , $start_two ) + $i , date( 'Y', $start_two ) );
$center_end = mktime( 23 , 59 , 59 , date( 'm' , $start_two ) , date( 'd' , $start_two ) + ( $i + 6 ) , date( 'Y' , $start_two ) );
// $start_two = $center_start;
$week[] = [ 'start' => $center_start , 'end' => $center_end ];
}
$week[] = $last;
return $week;
}