2 回答

TA貢獻(xiàn)1757條經(jīng)驗(yàn) 獲得超7個(gè)贊
一個(gè)快速的解決方法是獲取數(shù)組中的第一個(gè)和最后一個(gè)項(xiàng)目。
$consecutive_array = array_map(function($e){
if(!is_array($e)){
return $e;
}
$last = end($e);
return [reset($e), $last];
}, $consecutive_array);
或者按照評(píng)論中的建議使用min() max() 函數(shù)。
$consecutive_array = array_map(function($e){
if(!is_array($e)){
return $e;
}
return [min($e), max($e)];
}, $consecutive_array);

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
重要提示:不要指望strtodate一天比第二天的精確少 86400 秒strtodate- 根據(jù)服務(wù)器的區(qū)域設(shè)置,會(huì)有夏令時(shí),這可能會(huì)搞砸!
在這種情況下,我傾向于比較strtodate('+1 day',$timestampOfDay1)-strtodate($timestampOfDay2)這將包括夏令時(shí)。
這是我的做法:
//the dates
$dates =array (
'2018-10-15',
'2018-10-16',
'2018-10-17',
'2018-10-13',
'2018-10-19',
'2018-10-10',
'2018-10-11',
'2018-10-12',
'2018-10-22',
'2018-10-23',
'2018-10-29',
);
//call the function
$result = getConsecutive($dates);
//output
var_dump($result);
function getConsecutive($dates) {
sort($dates);
$result = [
'consecutive' => [],
'consecutive_count'=>0,
'non_consecutive' => []
];
$currentStart = null;
$currentTimestamp = null;
for ($i=0; $i<count($dates); $i++) {
$timestamp = strtotime($dates[$i]);
if ($currentStart == null) {
//first timestamp - set it as start & current
$currentStart = $timestamp;
$currentTimestamp = $timestamp;
} else if (strtotime('+1 day',$currentTimestamp) == $timestamp) {
//consecutive - keep waiting for a non-consecutive
$currentTimestamp = $timestamp;
} else {
if ($currentTimestamp == $currentStart) {
//we just got one
$result['non_consecutive'][] = date('Y-m-d',$currentTimestamp);
} else {
//we just got more then one, so they were consecutive
$result['consecutive']['dates'.(count($result['consecutive'])+1)] = [
date('Y-m-d',$currentStart),
date('Y-m-d',$currentTimestamp)
];
}
$currentStart = $timestamp;
$currentTimestamp = $timestamp;
}
}
//process the last timestamp
if ($currentTimestamp == $currentStart) {
//we just got one
$result['non_consecutive'][] = date('Y-m-d',$currentTimestamp);
} else {
//we just got more then one, so they were consecutive
$result['consecutive']['dates'.(count($result['consecutive'])+1)] = [
date('Y-m-d',$currentStart),
date('Y-m-d',$currentTimestamp)
];
}
$result['consecutive_count'] = count($result['consecutive']);
return $result;
}
- 2 回答
- 0 關(guān)注
- 115 瀏覽
添加回答
舉報(bào)