可能的重复:
检查一组内的连续日期并作为范围返回 https://stackoverflow.com/questions/8461543/check-for-consecutive-dates-within-a-set-and-return-as-range
我有一个从 mySQL 查询获得的日期数组。我需要将数组分成多个数组,以便每个数组中的日期是连续的。
所以,如果我从
$datearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08", "2013-06-19", "2013-06-20", "2013-06-21");
我需要能够将其分成
$firstdatearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08");
$seconddatearray = array("2013-06-29", "2013-06-30", "2013-07-01");
最后我将能够打印
3月5日至8日、6月29日至7月1日
我怎样才能做到这一点?我不知道从哪里开始。
这是完整的工作答案。 (享受!)
您必须循环遍历 $datearray 中的每个值
<?php
$datearray = array("2013-05-05", "2013-05-06", "2013-05-07", "2013-05-08", "2013-06-19", "2013-06-20", "2013-06-21");
asort($datearray);
$resultArray = array();
$index = -1;
$last = 0;
$out = "";
foreach ($datearray as $date) {
$ts = strtotime($date);
if (false !== $ts) {
$diff = $ts - $last;
if ($diff > 86400) {
$index = $index + 1;
$resultArray[$index][] = $date;
} elseif ($diff > 0) {
$resultArray[$index][] = $date;
} else {
// Error! dates are not in order from small to large
}
$last = $ts;
}
}
foreach ($resultArray as $a) {
if (count($a) > 1) {
$firstDate = $a[0];
$firstDateBits = explode('-',$firstDate);
$lastDate = $a[count($a)-1];
$lastDateBits = explode('-',$lastDate);
if ($firstDateBits[1] === $lastDateBits[1]) {
$out .= intval($firstDateBits[2]) . '-' . intval($lastDateBits[2]) . ' ' . date("M",strtotime($firstDate)) . ', ';
} else {
$out .= date("M d",strtotime($firstDate)) . '-' . date("M d",strtotime($lastDate)) . ', ';
}
}
}
这是输出:
5-8 May, 19-21 Jun
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)