【问题标题】:Fill out missing dates into associative array将缺失的日期填入关联数组
【发布时间】:2016-03-11 18:49:29
【问题描述】:

像这样在数组中添加缺失日期的最简单方法是什么? 它需要以正确的顺序排列,因为无法将数据添加到 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
)

【问题讨论】:

  • 没有for / foreach?
  • forDateTime 对象,创建一个包含所有日期的新数组

标签: php arrays sorting date add


【解决方案1】:

使用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;
}
?>

【讨论】:

  • 谢谢伙计!这些 cmets 真的很好,也可以理解。
【解决方案2】:

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

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

【讨论】:

  • 我没有得到年份的东西,代码中没有使用变量。
  • 那是我正在尝试的其他东西。我删除了它。
猜你喜欢
  • 2018-07-15
  • 2019-07-22
  • 2018-06-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-05
相关资源
最近更新 更多