How can PHP developers ensure the efficiency and accuracy of their scheduling algorithm when dealing with multiple overlapping time slots?
When dealing with multiple overlapping time slots, PHP developers can ensure the efficiency and accuracy of their scheduling algorithm by sorting the time slots based on their start times and then iterating through each time slot to check for overlaps. By keeping track of the current end time, developers can easily identify conflicts and adjust the schedule accordingly.
function scheduleEvents($events) {
usort($events, function($a, $b) {
return strtotime($a['start_time']) - strtotime($b['start_time']);
});
$schedule = [];
$currentEndTime = 0;
foreach ($events as $event) {
$startTime = strtotime($event['start_time']);
$endTime = strtotime($event['end_time']);
if ($startTime >= $currentEndTime) {
$schedule[] = $event;
$currentEndTime = $endTime;
}
}
return $schedule;
}
// Example usage
$events = [
['start_time' => '10:00', 'end_time' => '11:00'],
['start_time' => '10:30', 'end_time' => '12:00'],
['start_time' => '11:30', 'end_time' => '13:00'],
['start_time' => '12:30', 'end_time' => '14:00']
];
$schedule = scheduleEvents($events);
print_r($schedule);
Related questions
-
foreach array_map array_filter
-
SQL injection PHP scripts forum thread
-
PHP database columns character replacement