0

Can somebody please help me? I want to add dates from DatePeriod() to my array. I have the following code, which works, but it adds only the last row passed from SQL (the SQL query returns more than one start and end date):

while($rowLD = $getDataLD->fetch_assoc()) { 
  $strDateFrom = $rowLD['ld_time_start'];
  $strDateTo = $rowLD['ld_time_end'];
  $periodLD = new DatePeriod(new DateTime($strDateFrom), new DateInterval('P1D'), new DateTime($strDateTo.' +1 day'));
  
}

foreach ($periodLD as $dateLD) {
    $datesLD[] = $dateLD->format("Y-m-d");
}

Thank you.

1

2 Answers 2

0

You are just updating the $periodLD variable, it is not an array. It should be $periodLD[] = "your date period query" .

Sign up to request clarification or add additional context in comments.

5 Comments

Does not help, but thank you anyway.
Tell me why it doesn't work, it specifically answers your question. If you have any other errors, you can update your question.
I trust you that $periodLD should be defined as an array but that alone doesn't solve my issue. That's why I wrote that it doesn't help.
Then update your description and community is there for you to help.
Please vote to close duplicates instead of answering them. If you think a question might have been asked on Stack Overflow at any point in the last 14 years of feverish Q&A, please look for a duplicate page to flag with. When you answer duplicates, the Roomba cannot purge the redundant content. This puts unnecessary workload on humans to curate good content on this site. Thank you for your cooperation.
0

The problem is that you are overwriting $periodLD every time you assign to it. Since you want to end up with a single array composed of the elements returned by the (multiple) calls to new DatePeriod(), you must merge the period into your existing array:

$datesLD = [];
while($rowLD = $getDataLD->fetch_assoc()) { 
  $strDateFrom = $rowLD['ld_time_start'];
  $strDateTo = $rowLD['ld_time_end'];
  $period = new DatePeriod(new DateTime($strDateFrom), new DateInterval('P1D'), new DateTime($strDateTo.' +1 day'));
  foreach($period as $p) {
    $datesLD[] = $p->format('Y-m-d');
  }
}

1 Comment

Thank you, but it does not work. $period is not an array so it can't be merged.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.