返回多个日期范围之间的所有日期

时间:2016-12-13 16:43:41

标签: php date range

我试图混合几个php函数来获取多个日期范围之间的所有日期。

首先我使用了函数:

public function getDatesForArray($id){
       return $this->sqlQuery("SELECT date_from, date_to FROM bn_prereservation WHERE 
       oid='".$id."' AND status='ACCEPT' ORDER BY date_from ASC");
}

从我的数据库中获取所有数据范围。我得到的是这样的东西:

Array
(
[0] => Array
    (
        [date_from] => 2016-12-05
        [date_to] => 2016-12-08
    )

[1] => Array
    (
        [date_from] => 2016-12-11
        [date_to] => 2016-12-13
    )
)

接下来我使用了第二个函数,它应该返回这些数据范围之间的所有日期:

public function getReserv2($id){
      $dates = $this->getDatesforArray($id);
      $array = array();

      foreach($dates as list($start, $end)) {
            $format = 'Y-m-d'; 
            $interval = new DateInterval('P1D');
            $realStart = new DateTime($start);
            $realEnd = new DateTime($end);
            $realEnd->add($interval);


            $period = new DatePeriod($realStart, $interval, ($realEnd));

            foreach($period as $date) { 
                 $array[] = $date->format($format); 
            }
      }
      return $array;
}

我希望,我得到这样的东西:

2016-12-05
2016-12-06
2016-12-07
2016-12-08
2016-12-11
2016-12-12
2016-12-13

但我只得到:

2016-12-13
2016-12-13

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

来自Docs

  

list()仅适用于数值数组,并假设数字索引从0开始。

你试着"提取"一个关联数组:

foreach($dates as list($start, $end))

导致 E_NOTICE未定义偏移
(我想你已经把它关了。)

所以要解决你的问题:

function getReserv2($id){
  $dates = $this->getDatesforArray($id);
  $array = array();

  foreach($dates as $d) {
     // print_r($d);
     // list($start, $end) = $d; // THIS WONT WORK
        $format = 'Y-m-d'; 
        $interval = new DateInterval('P1D');
        $realStart = new DateTime($d['date_from']);  // get it directly from the array here
        $realEnd = new DateTime($d['date_to']);
        $realEnd->add($interval);

        $period = new DatePeriod($realStart, $interval, ($realEnd));

        foreach($period as $date) { 
             $array[] = $date->format($format); 
        }
  }
  return $array;
}

结果:

array(7) {
  [0]=>
  string(10) "2016-12-05"
  [1]=>
  string(10) "2016-12-06"
  [2]=>
  string(10) "2016-12-07"
  [3]=>
  string(10) "2016-12-08"
  [4]=>
  string(10) "2016-12-11"
  [5]=>
  string(10) "2016-12-12"
  [6]=>
  string(10) "2016-12-13"
}