Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add missing dates to an array

Tags:

php

I have the following array:

Array ( [2010-10-30] => 1 [2010-11-11] => 1 [2010-11-13] => 11 )

I am trying to fill in the array with all the missing dates between the first and last elements. I was attempting using the following but got nowhere:

foreach($users_by_date as $key => $value){
    $real_next_day = date($key, time()+86400);
    $array_next_day = key(next($users_by_date));
    if($real_next_day != $array_next_day){
      $users_by_date[$real_next_day] = $value;
    }
}
like image 244
user3450844 Avatar asked Sep 24 '26 04:09

user3450844


2 Answers

The DateTime, DateInterval and DatePeriod classes can really help out here.

$begin=date_create('2010-10-30');
$end=date_create('2010-11-13');
$i = new DateInterval('P1D');
$period=new DatePeriod($begin,$i,$end);

foreach ($period as $d){
  $day=$d->format('Y-m-d');
  $usercount= isset($users_by_date[$day]) ? $users_by_date[$day] :0;
  echo "$day $usercount"; 
}
like image 154
dnagirl Avatar answered Sep 26 '26 18:09

dnagirl


I have been waiting for a chance to try out DateTime and DateInterval objects in PHP 5.3, your question was the perfect opportunity to do just that. Note that this code will not work with PHP versions earlier than 5.3

<?php
$dates = array('2010-10-30' => 1, '2010-11-01' => 1, '2010-11-13' => 1);

// get start and end out of array
reset($dates);
$start = new DateTime(key($dates));

end($dates);
$end   = new DateTime(key($dates));

foreach (new DatePeriod($start, new DateInterval('P1D'), $end) as $date) {
    $dateKey = $date->format('Y-m-d'); // get properly formatted date out of DateTime object
    if (!isset($dates[$dateKey])) {
        $dates[$dateKey] = 1;
    }
}

print_r($dates);
like image 30
Anti Veeranna Avatar answered Sep 26 '26 16:09

Anti Veeranna



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!