我有一个排序的日期数组,如下所示:
$dates = Array('2014-10-01','2014-10-01','2014-10-02','2014-10-03','2014-10-05');
在这个数组中,我们有两次(有时候更多,但在我的脚本中是正常的)10月1日的日期,但它缺少第4次。
如何检测数组的第一个值与数组的最后一个值之间是否存在不连续性(同样,我的数组按升序日期排序)?
答案 0 :(得分:1)
$dates = array('2014-10-01','2014-10-01','2014-10-02','2014-10-03','2014-10-05');
$continued = true;
foreach ($dates as $key => $date) {
if (!empty($dates[$key+1])) {
$cDate = new DateTime($date);
$next = new DateTime($dates[$key+1]);
$interval = $next->diff($cDate);
if ($interval->d > 1) {
$continued = false;
}
}
}
$continued = false
然后出现不连续性。
答案 1 :(得分:1)
可能值得研究一下DateTime
课程及其好处。特别是DateTime::diff
,它返回DateInterval
个实例。这使您可以安全地减去2个日期,并确定这些日期之间的时间差异。 cf the manual。
简而言之,我已经整理了一个小函数,可用于确定日期字符串数组中的奇怪性:
$dates = array('2014-10-01','2014-10-01','2014-10-02','2014-10-03','2014-10-05');
$obj = array();
foreach ($dates as $date)
{//create an array of DateTime instances from the $dates values
$obj[] = new DateTime($date);
}
/**
* @param array $dates (an array of DateTime instances)
* @param string $intervalProperty = 'd' (valid valus are y, m, d, h, i, s)
* @param int $interval = null (the value $intervalProperty should have)
* @return array of null|DateInterval
*/
function getOddDiffs(array $dates, $intervalProperty = 'd', $interval = null)
{
$diffs = array();
for($i=0, $j=count($dates)-1;$i<$j;++$i)
{//iterate $dates
$diff = $dates[$i]->diff($dates[$i+1]);//compute diff
if ($interval === null && $diff->{$intervalProperty})
$interval = $diff->{$intervalProperty};//set $interval if needed/possible
if ($diff->{$intervalProperty} !== $interval)
{//if interval value !== $interval (type+value check required in case $interval is null)
$diffs[] = $diff;//return the diff
}
else
{
$diffs[] = null;//null means ok
}
}
return $diffs;//return results
}
如果你想看到它的实际效果:
答案 2 :(得分:0)
function hasDiscontinuities($dates)
{
// remove duplicates
$dates = array_unique($dates);
// get the last day
$parts = explode('-', end($dates));
$lastDay = (int) $parts[2];
// if the amount of dates is smaller than the last day, there must be discontinuities
if (count($dates) < $lastDay) {
return true;
}
return false;
}
关于Elias Van Ooteghem的评论#39;评论,重复现在被视为不连续:
function hasDiscontinuities($dates)
{
// duplicates count as discontinuities
if ($dates != array_unique($dates)) {
return true;
}
// get the last day
$parts = explode('-', end($dates));
$lastDay = (int) $parts[2];
// if the amount of dates is smaller than the last day, there must be discontinuities
if (count($dates) < $lastDay) {
return true;
}
return false;
}
第二次编辑是因为评论中添加了详细信息:
function hasDiscontinuities($dates)
{
// duplicates count as discontinuities
if ($dates != array_unique($dates)) {
return true;
}
$firstDate = new DateTime($dates[0]);
$lastDate = new DateTime(end($dates));
// if the difference in days is not the same as the amount of elements in the array, there are discontinuities
if (count($dates) != $lastDate->diff($firstDate)->days + 1) {
return true;
}
return false;
}