Fill out missing dates into associative array

2019-08-10 01:52发布

问题:

What would be the simplest way to add missing dates in array like this? It needs to be in the correct order though & since data can't be added in associative array with array_slice() I didn't find a way to do it without ending up with four foeach loops with converting into multidimensional array and converting back. Thanks!

    Array
(
    [1.1.2016] => 10
    [3.1.2016] => 5
    [5.1.2016] => 8
    [8.1.2016] => 3
)


Array
(
    [1.1.2016] => 10
    [2.1.2016] => 0
    [3.1.2016] => 5
    [4.1.2016] => 0
    [5.1.2016] => 8
    [6.1.2016] => 0
    [7.1.2016] => 0
    [8.1.2016] => 3
)

回答1:

Using DateTime's DatePeriod we can loop through the dates IF the dates are in the right order to start with. If it's possible that they are not in the right order to start with, you'll have to edit the begin and end DateTime

<?php
$newarray = array(); //Our new array
$myarray = array(...); //$myarray is your array that you have
reset($myarray); //Sets array position to start
$key = key($myarray); //Grabs the key
$begin = new DateTime( $key ); //Sets the begin date for period to $begin
end($myarray); //Sets array to end key
$key = key($myarray); //Gets end key
$end = new DateTime($key); //Sets end variable as last date
$end = $end->modify( '+1 day' ); //Includes the last day by adding + 1 day

$interval = new DateInterval('P1D'); //Increases by one day (interval)
$daterange = new DatePeriod($begin, $interval ,$end); //Gets the date range

foreach($daterange as $date){
    $date = $date->format("j.n.Y");
    if(isset($myarray[$date]))
        $newarray[$date] = $myarray[$date];
    else
        $newarray[$date] = 0;
}
?>


回答2:

This works no matter what the order the dates are in, though maybe you're limited to a year:

$dates = array("8.1.2016" => 100, "2.1.2016" => 5);


$date = "1.1.2016";
$m = null;
$fixed_dates = array();
while($m <= "12"){ 
  $fixed_dates[$date] = (isset($dates[$date]) ? $dates[$date] : 0);
  $edate = explode(".",$date);
  $m = $edate[0]+1;
  $date = implode(".",array($m,$edate[1],$edate[2]));
}

print_r($fixed_dates);