问题描述
像这样在数组中添加缺失日期的最简单方法是什么?
尽管&由于无法使用 array_slice()
将数据添加到关联数组中,所以我没有找到一种方法,而没有以四个foeach循环最终转换为多维数组和转换回来。谢谢!
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
)
推荐答案
使用 DateTime
的 DatePeriod
,我们可以循环查看日期如果日期在以正确的顺序开始。如果可能它们的开始顺序不正确,则必须编辑开始和结束 DateTime
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;
}
?>
这篇关于将缺少的日期填写到关联数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!