思路:获取当前时间 ,并拿到16点0的时间点,依次类推拿到15点 - 6点 的时间段统计的数据
以时间点为cachekey,第二次读取到的就不需要重复统计
部分代码:
获取时间节点的方法
// 时间节点 时间集合
public static function Tpoinsections($start,$hours)
{
//Interevel = 600 10min allhours =168 ,
$timeSections = [];
$timeIntervel ;
$startopoint = $start;
switch ($hours) {
case 1:
$timeIntervel = 10*60;
$m = floor(date("i", $start)/10)*10;
$startopoint = strtotime(date("Y-m-d H:".$m.":0", $start));
break;
case 8:
$timeIntervel = 3600;
$startopoint = strtotime(date("Y-m-d H",$start).":0:0");
break;
case 12:
$timeIntervel = 3600;
$startopoint = strtotime(date("Y-m-d H",$start).":0:0");
break;
case 168:
$timeIntervel = 24*3600;
$startopoint = strtotime(date("Y-m-d",$start)."0:0:0");
break;
default:
break;
}
$count = $hours*3600/$timeIntervel;//得到多少刻度
// [0]:($startpoint,$start); [1] $starpoint - hours
$timeSections[0]=[$start,$startopoint];
for ($i= 1; $i < $count ; $i++) {
$timeSections[$i]=[intval($startopoint)-($i-1)*$timeIntervel,intval($startopoint)-$i*$timeIntervel];
}
return $timeSections;
}
/**
*$len: time scale ;$day:
*/
// 缓存
public static function cahedata($sql,$where2,$timeSections,$cacheKey,$ylen,$hours)
{
$result= [];
$from = [];
$categories = [];
$cacheKeys=[];
$strdate='Y-m-d H:i:s';
$Expire = 1800;
foreach($timeSections as $i=> $timeSection) {
$timsec1 = $timeSection[0];
$categories[$i] = date($strdate,$timsec1);
if (\Cache::has($cacheKey.$timsec1)) {
$cacheKeys[$i] =$cacheKey.$timsec1;
$perCacheResult = \Cache::get( $cacheKey.$timsec1 );
$result[$i] = $perCacheResult;
$from[$i]='cached'.$timsec1;
}
else{
$where = " created_at > $timeSection[1] and created_at < $timeSection[0] ";
$sql2= $sql.$where.$where2;
$perResult = DB::select($sql2);
if($i!=0){ //当前第一个时间不缓存
\Cache::put($cacheKey.$timsec1,$perResult,$Expire);
}
$result[$i] = $perResult;
$from[$i]='db'.$timsec1;
}
}
//处理数据
$infos = json_encode($result);
$topinfo =json_decode($infos,true);
//stdClass转成数组,重点
$topinfo = (array)array_map(function($item){
return array_pluck($item, 'y');
}, $topinfo);
$result = array_pluck($topinfo, '0');//mysql语句 count(table_filed) as y
$data = array('result'=>$result,'from'=>$from,'date'=>$categories);
return $data;
}