将缺少的日期填写到关联数组中


Fill out missing dates into associative array

像这样在数组中添加缺失日期的最简单方法是什么?它需要按正确的顺序排列,并且由于数据无法添加到关联数组中array_slice()我没有找到一种方法来做到这一点,而不会以四个 foeach 循环结束转换为多维数组并转换回来。谢谢!

    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
)

使用 DateTimeDatePeriod我们可以循环访问日期,如果日期的开始顺序正确。如果它们的开始顺序可能不正确,则必须编辑开始和结束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;
}
?>

无论日期的顺序如何,这都有效,尽管您可能仅限于一年:

$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);