Sate Wedos
Sate Wedos

Reputation: 589

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

Upvotes: 1

Views: 748

Answers (2)

Syscall
Syscall

Reputation: 19779

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

Upvotes: 1

ild flue
ild flue

Reputation: 1361

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

Upvotes: 0

Related Questions