1. 程式人生 > >php 根據資料庫的開始時間和結束時間計算出天數 在根據天數迴圈對應的天數的次數

php 根據資料庫的開始時間和結束時間計算出天數 在根據天數迴圈對應的天數的次數

在專案的開發中  可能會遇到 這樣的需求

比如資料庫的欄位  start_time    end_time

開始時間  是 20180909

結束時間 是 20180913

那麼對應的 天數是4天的  那麼就要將該資料  迴圈4次

如下是select  查詢出來的 資料

 public function test1()
    {
        header("Access-Control-Allow-Origin: *");
        $y = date("Y", time());
        $m = date("m", time());
        $d = date("d", time());
        $t0 = date('t'); // 本月一共有幾天
        $start_month = mktime(0, 0, 0, $m, 1, $y); // 建立本月開始時間
        $end_month = mktime(23, 59, 59, $m, $t0, $y); // 建立本月結束時間
      
        $model = new AdvertModel();
        $data = $model->type_time($start_month, $end_month, $adsense_id);//這裡面有多條資料
        $ar = [];
       $data=$this->coun($data,$ar);
        if ($data) {
            exit(json_encode(array("status" => 1, "advert" => $data)));
        } else {
            exit(json_encode(array("status" => 0, "msg" => "當前沒有資料")));
        }
    }
    /*
     * 公共方法
     * 引數  data:  多條資料
     *       ar    宣告的陣列
     *      end_time   結束時間
     *      start_time  開始時間
     *      data_index  新的健名
     */
    public function coun($data,$ar,$end_time="end_time",$start_time="start_time",$date_index="date_index"){
        foreach ($data as $key =>$i) {
            $count_days=(($i[$end_time]- $i[$start_time])/60/60/24);
            if ($count_days>0){
                for ($j=0;$j<$count_days;$j++){
                    $date_index = date("Ymd",$i[$start_time]+ 3600*24*$j);
                    $i[$date_index] = $date_index ;
                    $ar[$date_index] = $i;
                }
            }
        }
        return $ar;
    }