简体   繁体   中英

Is there a way to find the closest time in an array of times in PHP?

I am a little bit stuck on something and wanted to know if you could help :-)

I have an array of times as so in PHP;

$arr = [
            '09:00:00',
            '10:00:00',
            '11:00:00',
            '12:00:00'
        ];

I am trying to build a function that'll accept a current date and time ie 2019-12-17 09:30:45 and spit out starting from the closest time ( 10:00:00 in this instance) to as many future values as needed. So if I were to ask for 6 I would expect;

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

Is there any sensible way to do this? As the avenues I'm exploring right now are a tad complicated and past my knowledge in PHP I'm afraid.

Thank you so much for taking the time to help on this, I really appreciate it.

First get the key of the closest value from the array $times and then in a for loop the next 6 values.

$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);

Output:

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',
) 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM