在PHP中从多个日期范围制作日期数组

92vpleto  于 2023-01-08  发布在  PHP
关注(0)|答案(2)|浏览(155)

我有代码来选择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行

imzjd6km

imzjd6km1#

对于结果的每一行,可以使用while() loop将数组中的每个日期相加。要管理日期,可以使用strtotime

while (odbc_fetch_row($sql))
{
    // grab our results
    $start  = odbc_result($sql, 'start');
    $finish = odbc_result($sql, 'finish');

    // convert date to timestamp
    $start_tm  = strtotime($start);
    $finish_tm = strtotime($finish);

    // add dates until $finish_tm reached
    while ($start_tm < $finish_tm)
    {
        // push new date 
        $dates[]  = date('Y-m-d', $start_tm);
        // move date marker to next day
        $start_tm = strtotime('+1 day', $start_tm);
    }
}
idfiyjo8

idfiyjo82#

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

<?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;
}

相关问题