一个简单的答案,对于缺乏实现感到抱歉,但是假设您使用的是5.3,并且日期按时间顺序排列,则可以将每个日期转换为一个
DateTime对象(如果尚未转换),然后使用
DateTime::diff()生成该对象的数组进行迭代一个
DateInterval可以用来将迭代中的当前日期与上一个日期进行比较的对象。您可以将连续的日期分组到子数组中,并使用
shift()和
pop()获取该子数组中的第一天和最后几天。
编辑
我对此有所考虑。接下来的工作很粗略,很容易实现,但是应该可以:
// assuming a chronologically// ordered array of DateTime objects$dates = array( new DateTime('2010-12-30'), new DateTime('2011-01-01'), new DateTime('2011-01-02'), new DateTime('2011-01-03'), new DateTime('2011-01-06'), new DateTime('2011-01-07'), new DateTime('2011-01-10'),);// process the array$lastDate = null;$ranges = array();$currentRange = array();foreach ($dates as $date) { if (null === $lastDate) { $currentRange[] = $date; } else { // get the DateInterval object $interval = $date->diff($lastDate); // DateInterval has properties for // days, weeks. months etc. You should // implement some more robust conditions here to // make sure all you're not getting false matches // for diffs like a month and a day, a year and // a day and so on... if ($interval->days === 1) { // add this date to the current range $currentRange[] = $date; } else { // store the old range and start anew $ranges[] = $currentRange; $currentRange = array($date); } } // end of iteration... // this date is now the last date $lastDate = $date;}// messy... $ranges[] = $currentRange;// print datesforeach ($ranges as $range) { // there'll always be one array element, so // shift that off and create a string from the date object $startDate = array_shift($range); $str = sprintf('%s', $startDate->format('D j M')); // if there are still elements in $range // then this is a range. pop off the last // element, do the same as above and concatenate if (count($range)) { $endDate = array_pop($range); $str .= sprintf(' to %s', $endDate->format('D j M')); } echo "<p>$str</p>";}输出:
Thu 30 DecSat 1 Jan to Mon 3 JanThu 6 Jan to Fri 7 JanMon 10 Jan



