DS9
DS9

Reputation: 3033

How to find free time slot based on available time slot and booked time slot?

I have one user A. The User A is available for 10:45:00 to 18:45:00. means he can accept appointments during that time.

so suppose, User A has two booked appointments:
(1) 11:15:00 to 12:15:00 and
(2) 13:30:00 to 15:45:00

There is minimum 10 minutes gap between two appointment.

So now User A's free timing is:

(1) 10:45:00 to 11:05:00 ( start time = 10:45:00, end time = 11:05:00 because user A have booked appointment which is start at 11:15:00, there is 10 min gap between time so end time is 11:05:00)

(2) 12:25:00 to 13:20:00 (start time = 12:25:00 because first booked appointment is finished on 12:15:00, there is 10 min gap between time so end time is 12:25:00, end time = 13:20:00 because 2nd booked appointment is started on 13:30:00, there is 10 min gap between time so end time is 13:20:00 )

(3) 15:55:00 to 18:45:00 (same as above)

means

Total Time Slot:
10:45:00 to 18:45:00

Booked Time Slot:
11:15:00 to 12:15:00
13:30:00 to 15:45:00

Free Time Slot:
10:45:00 to 11:05:00
12:25:00 to 13:20:00
15:55:00 to 18:45:00

PHP CODE:

$total_time = array(
    'time' => '11:15:00',
    'end_time' => '12:15:00'
);

$gettime = $this->db->query("select `appointment_id`, `time`, `end_time` from `tbl_appointment` where `date`='".$json['date']."'");
if($gettime->num_rows()>0) 
{
    foreach($gettime->result_array() as $restime)
    {
        $booked_time[] = array(
            'time' => $restime['time'],
            'end_time' => $restime['end_time']
        );
    }
}

I have no idea about how to implement it, so i have no other code. Just two array.
So question is based on available time and booked time, how to find free time?

Thanks in advance.

Upvotes: 2

Views: 6038

Answers (1)

Michel
Michel

Reputation: 4157

Basic solution (maybe not the best, but at least a start)

The idea: make an array of 5-minute blocks from workday-start to workday end. Fill it with 0. Every time an appointment is made, put it in 5-minute blocks and put it in the array as 1. Now you know per block if someone is available.

//working hours
$start='10:45:00';
$end='18:45:00';
$start=strtotime($start);
$end=strtotime($end);

//end-start divided by 300 sec to create a 5 min block
$timesegments=($end-$start)/300;
//create the blocks-array
$blocks=array_fill_keys(range(0,$timesegments,5),0);

//an appointment
$app_start='10:45:00';
$app_end='11:00:00';

//make 5 minute blocks (note that workday start is 0!)
$app_start=(strtotime($app_start)-$start)/300;
$app_end=(strtotime($app_end)-$start)/300;

//put it in the blocks-array (+2 for 10 minute break)
for($i=$app_start;$i<$app_end+2;++$i){
    $blocks[$i]=1;
    }

echo '<pre>'.print_r($blocks,true).'</pre>';

This is very basic and without any checks, but I hope you can use it.

Upvotes: 4

Related Questions