大家好我有一个填充了日期的数组
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语句没有输出 - UPDATED -
$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');
}
}
答案 0 :(得分: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');
}
答案 1 :(得分: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 "; };
答案 2 :(得分: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;
});
?>