Created
July 31, 2019 06:18
-
-
Save aalipar13/5a6832d8b3c89c30b438c55120e904c4 to your computer and use it in GitHub Desktop.
PHP - add missing date in array (from: https://stackoverflow.com/questions/46380370/add-missing-date-index-to-array-in-php)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$arr = [ | |
['date' => '2019-07-31', 'total' => 4], | |
['date' => '2019-08-04', 'total' => 6], | |
['date' => '2019-08-05', 'total' => 7] | |
]; | |
$result = []; | |
foreach ($arr as $k => $item) { | |
$d = new DateTime($item['date']); | |
$result[] = $item; | |
if (isset($arr[$k+1])) { | |
$diff = (new DateTime($arr[$k+1]['date']))->diff($d)->days; | |
if ($diff > 1) { | |
$result = array_merge($result , array_map(function($v) use($d){ | |
$d_copy = clone $d; | |
// do something here if date doesn't exist | |
return [ | |
'date' => $d_copy->add(new DateInterval('P' . $v. 'D'))->format('Y-m-d'), | |
'total' => 0 | |
]; | |
}, range(1, $diff-1))); | |
} | |
} | |
} | |
echo "<pre>"; | |
print_r($result); | |
echo "</pre>"; | |
die; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment