Skip to content

Instantly share code, notes, and snippets.

@alexalannunes
Last active July 5, 2021 16:46
Show Gist options
  • Select an option

  • Save alexalannunes/596888b2ef4b26f3b43948f90809b949 to your computer and use it in GitHub Desktop.

Select an option

Save alexalannunes/596888b2ef4b26f3b43948f90809b949 to your computer and use it in GitHub Desktop.
fill missing dates with ZERO
<?php
$d1 = '2021-07-01';
$d2 = '2021-07-10';
$dados = [
[
"data" => "2021-07-01",
"value" => 10,
],
[
"data" => "2021-07-02",
"value" => 10,
],
[
"data" => "2021-07-03",
"value" => 10,
],
// [
// "data" => "2021-07-01",
// "value" => 10,
// ],
[
"data" => "2021-07-05",
"value" => 10,
],
[
"data" => "2021-07-08",
"value" => 555,
],
];
$newArray = [];
$i = 0;
$indexFounded = 0;
while ($d1 <= $d2) {
$d = array_filter($dados, function ($item) use ($d1) {
return ($item['data'] == $d1);
});
if (count($d)) {
$newArray[] = $d[$indexFounded];
$indexFounded++;
} else {
$newArray[$i]["data"] = $d1;
$newArray[$i]["value"] = 0;
}
$d1 = date('Y-m-d', strtotime('+ 1 Day', strtotime($d1)));
$i++;
}
echo "--------------------------\n";
print_r($newArray);
// Array
// (
// [0] => Array
// (
// [data] => 2021-07-01
// [value] => 10
// )
// [1] => Array
// (
// [data] => 2021-07-02
// [value] => 10
// )
// [2] => Array
// (
// [data] => 2021-07-03
// [value] => 10
// )
// [3] => Array
// (
// [data] => 2021-07-04
// [value] => 0
// )
// [4] => Array
// (
// [data] => 2021-07-05
// [value] => 10
// )
// [5] => Array
// (
// [data] => 2021-07-06
// [value] => 0
// )
// [6] => Array
// (
// [data] => 2021-07-07
// [value] => 0
// )
// [7] => Array
// (
// [data] => 2021-07-08
// [value] => 555
// )
// [8] => Array
// (
// [data] => 2021-07-09
// [value] => 0
// )
// [9] => Array
// (
// [data] => 2021-07-10
// [value] => 0
// )
// )
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment