В приведенном ниже коде показано, как получить все используемые слоты (на основе интервала).
<?php
$pitchStart = new DateTime('2018-06-11 08:00 AM');
$pitchClose = new DateTime('2018-06-11 09:00 PM');
$games = [
[
'start' => new DateTime('2018-06-11 09:00 AM'),
'end' => new DateTime('2018-06-11 10:00 AM')
],
[
'start' => new DateTime('2018-06-11 10:30 AM'),
'end' => new DateTime('2018-06-11 10:43 AM')
],
[
'start' => new DateTime('2018-06-11 11:00 AM'),
'end' => new DateTime('2018-06-11 11:55 AM')
]
];
//This is the time slots interval
$slot_interval = new DateInterval("PT30M"); //30 Minutes
//Get all slots between $pitchStart and $pitchClose
$all_slots = [];
$slots_start = $pitchStart;
$slots_end = $pitchClose;
//This is how you can generate the intervals based on $pitchStart / $pitchClose and $slot_interval
while($slots_start->getTimestamp() < $slots_end->getTimestamp()) {
$all_slots[] = [
'start' => clone $slots_start,
'end' => (clone $slots_start)->add($slot_interval)
];
$slots_start->add($slot_interval);
}
function slots_used_by_game($slots, $games, $slot_interval) {
$slots_taken = [];
foreach($games as $game){
$game_duration = $game['end']->diff($game['start']);
$game_duration_in_minutes = (float)($game_duration->h * 60 + $game_duration->i);
$number_of_slots = ceil($game_duration_in_minutes / $slot_interval);
foreach($slots as $key => $slot) {
if($game['start'] <= $slot['start']) {
$slots_taken = array_merge($slots_taken, array_slice($slots, $key, $number_of_slots));
break;
}
}
}
return $slots_taken;
}
$used_slots = slots_used_by_game($all_slots, $games, 30);
//Print them all for testing
foreach($all_slots as $slot) {
echo $slot['start']->format('Y-m-d H:i'). ' - '.$slot['end']->format('Y-m-d H:i').PHP_EOL;
echo ((in_array($slot, $used_slots)) ? 'NOT AVAILABLE' : 'AVAILABLE').PHP_EOL;
echo PHP_EOL;
}