我有点坚持不懈,想知道您是否可以提供帮助:-)
在PHP中,我有很多时间;
$arr = [
'09:00:00',
'10:00:00',
'11:00:00',
'12:00:00'
];
我正在尝试构建一个接受当前日期和时间的函数,即2019-12-17 09:30:45
并从最近的时间(在这种情况下为10:00:00
)吐出到所需的将来值。因此,如果我要6个,我会期望的;
2019-12-17 10:00:00
2019-12-17 11:00:00
2019-12-17 12:00:00
2019-12-18 09:00:00
2019-12-18 10:00:00
2019-12-18 11:00:00
有什么明智的方法吗?由于我现在正在探索的途径有些复杂,因此恐怕我对PHP的了解还不够。
非常感谢您抽出宝贵的时间对此提供帮助,我真的很感激。
答案 0 :(得分:1)
首先从$ times数组中获取最接近值的键,然后在for循环中获取接下来的6个值。
$times = ['09:00:00','10:00:00','11:00:00','12:00:00'];
$start = "2019-12-17 09:30:45";
$number = 6;
$countTime = count($times);
$result = [];
sort($times);
list($startDate,$startTime) = explode(" ",$start);
//calculate the closest time
$timeDiff = 100000;
foreach($times as $key => $time){
$curDiff = abs(strtotime($time)-strtotime($startTime));
if($curDiff < $timeDiff){
$timeDiff = $curDiff;
$cKey = $key;
}
}
//calculate dates
for($i=0; $i<$number; $i++){
$result[] = $startDate." ".$times[$cKey++];
if($cKey >= $countTime){
$startDate = date('Y-m-d',strtotime($startDate.' + 1 Day'));
$cKey = 0;
}
}
echo "<pre>";
var_export($result);
输出:
array (
0 => '2019-12-17 10:00:00',
1 => '2019-12-17 11:00:00',
2 => '2019-12-17 12:00:00',
3 => '2019-12-18 09:00:00',
4 => '2019-12-18 10:00:00',
5 => '2019-12-18 11:00:00',
)