按日期过滤数组

时间:2015-07-14 10:36:21

标签: php arrays php-5.3

所以我有以下数组:

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)但它不起作用。请帮帮我。 Thx提前。存在解决方案吗?

3 个答案:

答案 0 :(得分:1)

这样的事情可能会对你有所帮助:

<?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)
}

答案 1 :(得分:0)

TIdImap4

答案 2 :(得分:0)

您可以为此创建自定义函数,请参阅下面的示例: 目前它仅从开始日起工作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
)