所以我有以下数组:
Array
(
[2015-07-10] => 94
[2015-07-07] => 20
[2015-07-13] => 6
[2015-07-09] => 42
[2015-07-08] => 48
)
这个数组从最近7天获得数据,现在我想按日期过滤这个数组,如果数据不存在,添加value = 0。例如,如果今天执行这个cron,所以我需要从07-07-2014 ---- 14-07-2014获取数据,对于我的例子,我需要像这样转换数组:
Array
(
[2015-07-07] => 20
[2015-07-08] => 48
[2015-07-09] => 42
[2015-07-10] => 94
[2015-07-11] => 0
[2015-07-12] => 0
[2015-07-13] => 6
[2015-07-14] => 0
)
我试着做一个ksort这样:ksort($aFilterdFlashParties)
,但它没有工作。请帮帮我。提前感谢。存在解决方案吗?
可能像这样的东西可以帮助你:
<?php
$dateArray = [
'2015-07-10' => 94,
'2015-07-07' => 20,
'2015-07-13' => 6,
'2015-07-09' => 42,
'2015-07-08' => 48,
];
$begin = new DateTime( '2015-07-07' );
$end = new DateTime( '2015-07-14' );
$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);
foreach ( $period as $dt ) {
$date = $dt->format( "Y-m-d" );
if (!isset($dateArray[$date])) {
$dateArray[$date] = 0;
}
}
ksort($dateArray);
var_dump($dateArray);
?>
输出:{
["2015-07-07"]=>
int(20)
["2015-07-08"]=>
int(48)
["2015-07-09"]=>
int(42)
["2015-07-10"]=>
int(94)
["2015-07-11"]=>
int(0)
["2015-07-12"]=>
int(0)
["2015-07-13"]=>
int(6)
}
$input = [
'2015-07-10' => 94,
'2015-07-07' => 20,
'2015-07-13' => 6,
'2015-07-09' => 42,
'2015-07-08' => 48
];
// Dates range
$StartDate = '07-07-2015';
$EndDate = '14-07-2015';
// Make array date =>0
$i = strtotime($StartDate);
$iEnd = strtotime($EndDate);
$dates = [];
While ($i <= $iEnd) {
$dates[date('Y-m-d', $i)] = 0;;
$i = strtotime('+1day', $i);
}
// Set existing data
$res = array_replace($dates, $input);
print_r($res);
你可以创建一个自定义函数,见下面的例子:目前它只适用于7天从开始的日子,你可以根据需要定制它更多。
$array = Array
(
'2015-07-10' => 94,
'2015-07-07' => 20,
'2015-07-13' => 6,
'2015-07-09' => 42,
'2015-07-08' => 48
);
function getExpectedArray($startDate, $dates){
$endDate = date('Y-m-d', strtotime($startDate . ' +7day'));
$startDate = date('Y-m-d', strtotime($startDate));
$nArray = array();
if($startDate < $endDate){
while($startDate <= $endDate){
if(array_key_exists($startDate, $dates)){
$nArray[$startDate] = $dates[$startDate];
} else {
$nArray[$startDate] = 0;
}
$startDate = date('Y-m-d', strtotime($startDate . "+1day"));
}
}
return $nArray;
}
echo '<pre>';
print_r(getExpectedArray('2015-07-07', $array));
输出:Array
(
[2015-07-07] => 20
[2015-07-08] => 48
[2015-07-09] => 42
[2015-07-10] => 94
[2015-07-11] => 0
[2015-07-12] => 0
[2015-07-13] => 6
[2015-07-14] => 0
)