在PHP中,有没有一种方法可以在时间数组中找到最近的时间?

在PHP中,有没有一种方法可以在时间数组中找到最近的时间?,php,datetime,Php,Datetime,我有点迷糊了,想知道你是否能帮忙:-) 我有一个数组的时间,所以在PHP $arr = [ '09:00:00', '10:00:00', '11:00:00', '12:00:00' ]; 我正在尝试构建一个函数,该函数将接受当前日期和时间,即2019-12-17 09:30:45,并根据需要从最近的时间(10:00:00在本例中)开始吐出尽可能多的未来值。因此,如果我要求6,我会

我有点迷糊了,想知道你是否能帮忙:-)

我有一个数组的时间,所以在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了


非常感谢您在这方面花时间提供帮助,我非常感谢。

首先从数组$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);

首先从数组$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);

一步一步地工作:1)你设法得到最近的一小时了吗?试着计算一下当前小时和那些小时之间的差异,也许,2)之后,你只需要对每一个小时做一些更改,然后在你的数组中的最后一个小时之后再加上一天!这就是我自己要走的路:-)谢谢!一步一步地工作:1)你设法得到最近的一小时了吗?试着计算一下当前小时和那些小时之间的差异,也许,2)之后,你只需要对每一个小时做一些更改,然后在你的数组中的最后一个小时之后再加上一天!这就是我自己要走的路:-)谢谢!那正是我要找的。干杯!那正是我要找的。干杯!