0

大家好,我有一个包含日期的数组

Array
(
    [0] => 2012-04-04
    [1] => 2012-04-06
    [2] => 2012-04-06
    [3] => 2012-04-06
    [4] => 2012-04-06
    [5] => 2012-04-06
    [6] => 2012-04-06
    [7] => 2012-04-11
    [8] => 2012-04-12
    [9] => 2012-04-12
    [10] => 2012-04-13
    [11] => 2012-04-13
    [12] => 2012-04-13
    [13] => 2012-04-13
    [14] => 2012-04-13
    [15] => 2012-04-13
    [16] => 2012-04-13
)

我将如何遍历数组并找到数组中相邻项目之间的天数差异。例如,我想回显

[0] 和 [1] 之间的差异是“2”天 [1] 和 [2] 之间的差异是“0”天

:)

设法从最佳答案中获得一些输出,但是我只希望它在日期存在差异时显示。

虽然这个 if 语句没有输出 - 更新 -

$count = count($datestack);



for ($i = 0; $i < $count - 1; $i++) {
    $datetime1 = new DateTime($datestack[$i]);
    $datetime2 = new DateTime($datestack[$i + 1]);
    $interval = $datetime1->diff($datetime2);
    if ($arr[$i] === $arr[$i+1]){
     echo $interval->format('%R%a days');
    }

} 
4

3 回答 3

3

你需要的是DateTime::diff

例子:

$datetime1 = new DateTime('2012-04-04');
$datetime2 = new DateTime('2012-04-06');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

你只需要循环你的数组来做你想做的事。

$count = count($arr);
for ($i = 0; $i < $count - 1; $i++) {
    $datetime1 = new DateTime($arr[$i]);
    $datetime2 = new DateTime($arr[$i + 1]);
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%R%a days');
} 
于 2012-03-29T02:27:50.903 回答
0

像这样?

     foreach($input as $k=>$i){ if(empty($input[$k-1])) continue; echo "<br /> difference between [".($k-1)."] and [".$k."] is ".'"'.round(abs(strtotime($i)-strtotime($input[$k-1]))/(3600*24)).'"'." days "; };
于 2012-03-29T02:33:35.707 回答
0
<?php 
    $dates = array(
        '2012-04-04',
        '2012-04-06',
        '2012-04-06',
        '2012-04-06',
        '2012-04-06',
        '2012-04-06',
        '2012-04-06',
        '2012-04-11',
        '2012-04-12',
        '2012-04-12',
        '2012-04-13',
        '2012-04-13',
        '2012-04-13',
        '2012-04-13',
        '2012-04-13',
        '2012-04-13',
        '2012-04-13'
   );

   array_walk($dates, function($item, $key) {
        static $previous = null;
        if ($previous != null) {
            $datetime1 = new DateTime($previous);
            $datetime2 = new DateTime($item);
            $interval = $datetime1->diff($datetime2);
            echo $interval->format('%R%a days') . "\n";
        } 
        $previous = $item;
   }); 

?>   
于 2012-03-29T03:47:33.717 回答