1

Having this snippet for buffering events.

$temp = array();

while ($row = $source)
{
  $temp[] = $row;

   // `add_day` means how many of next days add to buffer

   $d = new DateTime($row->date);

   for ($i = 0; $i < $row->add_day; $i++)
   {
      $d->modify('+1 day');          

      $row->date = $d->format('Y-m-d');

      $temp[] = $row;

      // print_r($row) --> It's OK. `date` has proper value.
   }
}

While tracking single event, everything seems to be fine. But in the result - $temp array, all rows from forcycle have the same date value. (the last one.)

E.G.

$data = { date: '2015-07-01', add_day: 2 }

Result:

$temp[0] = { date: '2015-07-03'} 
$temp[1] = { date: '2015-07-03'}
$temp[2] = { date: '2015-07-03'}  

Where I am doing a mistake??

1 Answer 1

3

You keep overwriting the value for that date in your object. Since that array has references to the same object they all return the same value.

for ($i = 0; $i < $row->add_day; $i++)
{
    $d->modify('+1 day');          
    // Here you keep updating your object to have the new date
    $row->date = $d->format('Y-m-d');
    $temp[] = $row;
}

Cloning those objects is one way to work around this:

for ($i = 0; $i < $row->add_day; $i++)
{
    $d->modify('+1 day');    
    $tempObj = clone $row;      
    $tempObj->date = $d->format('Y-m-d');
    $temp[] = $tempObj;
}
Sign up to request clarification or add additional context in comments.

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.