您拥有的所有日期都在同一年。您可以将每个日期转换为当年的天数。
然后你会有一个数字数组。对于该数组,您可以像这里概述的那样做:
另一种方法是根据前一个日期计算下一个日期,然后将其与数组中的下一个日期进行比较。如果两者相等,则延长当前时间跨度,否则,创建一个新的时间跨度。然后将数组减少到时间跨度:
$consecutiveDates = function ($result, $date) {
if ($count = count($result)) {
$next = clone $result[$count - 1][1];
$next->add(new DateInterval('P1D'));
}
$date = new DateTime($date);
if (!$count || $date != $next) {
$result[$count++] = [$date];
}
$result[$count - 1][1] = $date;
return $result;
};
$reduced = array_reduce($datearray, $consecutiveDates, []);
这给出了以下结果(对于您的数组):
Array
(
[0] => Array
(
[0] => DateTime Object
(
[date] => 2013-05-05 00:00:00
[timezone_type] => 3
[timezone] => Europe/London
)
[1] => DateTime Object
(
[date] => 2013-05-08 00:00:00
[timezone_type] => 3
[timezone] => Europe/London
)
)
[1] => Array
(
[0] => DateTime Object
(
[date] => 2013-06-19 00:00:00
[timezone_type] => 3
[timezone] => Europe/London
)
[1] => DateTime Object
(
[date] => 2013-06-21 00:00:00
[timezone_type] => 3
[timezone] => Europe/London
)
)
)
这两个条目现在可以使用映射函数轻松映射到您的输出样式中:
$consecutiveDatesString = function ($pair) {
list($start, $end) = $pair;
return $start == $end
? $start->format('j M')
: $start->format($start->format('M') != $end->format('M') ? 'j M' : 'j')
. $end->format(' - j M');
};
$consecutiveDatesStrings = array_map($consecutiveDatesString, $reduced);
然后导致更紧凑的结果:
Array
(
[0] => 5 - 8 May
[1] => 19 - 21 Jun
)
最后打印逗号分隔的:
echo implode(', ', $consecutiveDatesStrings), "\n";
这给出了,你猜怎么着:
5 - 8 May, 19 - 21 Jun