1

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

2 Answers 2

1

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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.