将缺失的日期填充到关联数组中

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