在PHP中从多个日期范围创建日期数组

时间:2018-01-22 07:33:16

标签: php mysql arrays while-loop

我有选择SQL Server的代码:

<?php
include "koneksi.php";
$sql=odbc_exec($koneksi,"select * from trip");
while(odbc_fetch_row($sql)){
$no=odbc_result($sql,"number");
$start=odbc_result($sql,"start");
$finish=odbc_result($sql,"finish");
}
?>

此循环包含以下数据:

|No|   Start  |  Finish  |
|1 |2018-01-01|2018-01-05|
|2 |2018-01-10|2018-01-13|

我想制作这样的数组:

array(
"2018-01-01",
"2018-01-02",
"2018-01-03",
"2018-01-04",
"2018-01-05",
"2018-01-10",
"2018-01-11",
"2018-01-12",
"2018-01-13"
);

如何从此日期范围创建数组?

  

注意:循环可以超过2行

2 个答案:

答案 0 :(得分:1)

您可以尝试这样的事情:

while (...) {

    $start=odbc_result($sql,"start");
    $finish=odbc_result($sql,"finish");


    $start_tm = strtotime($start) ;
    $finish_tm = strtotime($finish) ;

    while ($start_tm < $finish_tm) {
        $dates[] = date('Y-m-d', $start_tm) ;
        $start_tm = strtotime('+1 day', $start_tm) ;
    }

}

答案 1 :(得分:0)

这是关于如何获取数组的示例:

<?php
while(odbc_fetch_row($sql)){
  $no=odbc_result($sql,"number");
  $start=odbc_result($sql,"start");
  $finish=odbc_result($sql,"finish");
  $arr = addIntoArray($arr, $start, $finish);   
}

function addIntoArray($arr, $start, $end) {
  $ts1 = strtotime($start);
  $ts2 = strtotime($end);
  for($ts=$ts1; $ts<=$ts2; $ts=$ts+86400)  {
    $arr[] = date('Y-m-d', $ts);
  }
  sort($arr);
  return $arr;
}