简体   繁体   中英

Make date array from multiple date range in PHP

I have code to select 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");
}
?>

This loop contains the following data:

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

I want to make array like this:

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"
);

How can I create an array from this date range?

NB: looping can be more than 2 lines

For each row of the results, you can use a while() loop to add each date inside your array. To manage date, you can use 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);
    }
}

This is an example on how to get the array:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM