Possible Duplicate:
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");
终于可以打印了
5 - 8 Mar, 29 Jun - 1 Jul
我该怎么做?我不知道从哪里开始。
这是完整的工作答案。 (享受吧!)
您必须遍历 $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