laravel + memcache 截止到目前為止12小時內的資料
思路:獲取當前時間 ,並拿到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;
}