Skip to content

Instantly share code, notes, and snippets.

@RobinDev
Last active August 29, 2015 14:07
Show Gist options
  • Save RobinDev/c36d6d1f011c4a83969e to your computer and use it in GitHub Desktop.
Save RobinDev/c36d6d1f011c4a83969e to your computer and use it in GitHub Desktop.
PHP function `normalizeDateKeys` wich convert a php array with date keys in a pĥp array with date keys wich are following itself day by day
<?php
/**
* Convert a php array with date in a pĥp array with date wich are following itself day by day
*
* @param array $date containing the date
* @param bool $dateInKey must be set to true if the dates are in the array's keys
* @param string $fDate relative to the date format relative to php date's function
* @return array with every one key for every day
*/
function normalizeDateArray(array $dates, $dateInKey = false, $fDate = 'Y-m-d') {
$sort = $dateInKey === true ? 'ksort' : 'sort';
$sort($dates);
foreach($dates as $k => $v) {
$date = date('Ymd', strtotime($dateInKey === true ? $k : $v));
if(!isset($prev_date)) {
$prev_date = strtotime($date);
continue;
}
while($date > date('Ymd', strtotime('+1 day', $prev_date))) {
$prev_date = strtotime('+1 day', $prev_date);
if($dateInKey===true) {
$dates[date($fDate, $prev_date)] = 0;
} else {
$dates[] = date($fDate, $prev_date);
}
}
$prev_date = strtotime($date);
}
$sort($dates);
return $dates;
}
var_dump(normalizeDateArray(array('2014-09-01' => 13, '2014-08-02' =>12), true));
/**
* Will return :
array(31) {
["2014-08-02"]=>
int(12)
["2014-08-03"]=>
int(0)
["2014-08-04"]=>
int(0)
["2014-08-05"]=>
int(0)
["2014-08-06"]=>
int(0)
["2014-08-07"]=>
int(0)
["2014-08-08"]=>
int(0)
["2014-08-09"]=>
int(0)
["2014-08-10"]=>
int(0)
["2014-08-11"]=>
int(0)
["2014-08-12"]=>
int(0)
["2014-08-13"]=>
int(0)
["2014-08-14"]=>
int(0)
["2014-08-15"]=>
int(0)
["2014-08-16"]=>
int(0)
["2014-08-17"]=>
int(0)
["2014-08-18"]=>
int(0)
["2014-08-19"]=>
int(0)
["2014-08-20"]=>
int(0)
["2014-08-21"]=>
int(0)
["2014-08-22"]=>
int(0)
["2014-08-23"]=>
int(0)
["2014-08-24"]=>
int(0)
["2014-08-25"]=>
int(0)
["2014-08-26"]=>
int(0)
["2014-08-27"]=>
int(0)
["2014-08-28"]=>
int(0)
["2014-08-29"]=>
int(0)
["2014-08-30"]=>
int(0)
["2014-08-31"]=>
int(0)
["2014-09-01"]=>
int(0)
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment