如何将带有日期的数组减去另一个带有日期的数组

时间:2016-04-20 22:49:57

标签: php arrays date

我有两个数组,其中包含开始日期和结束日期等日期,希望两个日期之间有所不同。

开始日期

Array
(
    [0] => 2016-05-25
    [1] => 2016-05-25
    [2] => 2016-05-25
    [3] => 2016-05-25
    [4] => 2016-05-25
    [5] => 2016-05-25
)

结束日期

Array
(
    [0] => 2016-05-28
    [1] => 2016-05-28
    [2] => 2016-05-28
    [3] => 2016-05-28
    [4] => 2016-05-28
    [5] => 2016-05-28
)   

想要输出

Array
(
    [0] => 3
    [1] => 3
    [2] => 3
    [3] => 3
    [4] => 3
    [5] => 3
)

1 个答案:

答案 0 :(得分:2)

假设您的数组大小相同,数组名称为$startDates$endDates

$differences = array();
for($i=0;$i<=count($startDates)-1;$i++)
{
   // we divide by 86400 since 86400 seconds per day
   $differences[] = (strtotime($endDates[$i]) - strtotime($startDates[$i])) / 86400;
}

您还可以使用DateTime方法使用diff方法来获取它们之间的差异(可能更好的主意,避免可能除以零问题)。

http://php.net/manual/en/datetime.diff.php

$differences = array();
for($i=0;$i<=count($startDates)-1;$i++)
{
   $date1 = new DateTime($endDates[$i]);
   $date2 = new DateTime($startDates[$i]);
   $interval = $date1->diff($date2);
   $differences[] = $interval->format('%a');
}

编辑:因为您评论它不起作用:

$startDates = [
    '2016-05-25',
    '2016-05-25',
    '2016-05-25',
    '2016-05-25',
    '2016-05-25'
];

$endDates = [
    '2016-05-28',
    '2016-05-28',
    '2016-05-28',
    '2016-05-28',
    '2016-05-28'
];

$differences = array();
for($i=0;$i<=count($startDates)-1;$i++)
{
   // we divide by 86400 since 86400 seconds per day
   $differences[] = (strtotime($endDates[$i]) - strtotime($startDates[$i])) / 86400;
}

var_dump($differences);

结果:

array(5) {
  [0]=>
  int(3)
  [1]=>
  int(3)
  [2]=>
  int(3)
  [3]=>
  int(3)
  [4]=>
  int(3)
}

DateTime方法:

$startDates = [
    '2016-05-25',
    '2016-05-25',
    '2016-05-25',
    '2016-05-25',
    '2016-05-25'
];

$endDates = [
    '2016-05-28',
    '2016-05-28',
    '2016-05-28',
    '2016-05-28',
    '2016-05-28'
];

$differences = array();
for($i=0;$i<=count($startDates)-1;$i++)
{
   $date1 = new DateTime($endDates[$i]);
   $date2 = new DateTime($startDates[$i]);
   $interval = $date1->diff($date2);
   $differences[] = $interval->format('%a');
}

结果:

array(5) {
  [0]=>
  int(3)
  [1]=>
  int(3)
  [2]=>
  int(3)
  [3]=>
  int(3)
  [4]=>
  int(3)
}