Reputation: 3356
I have a loop which gives an outcome of number of half hours between given start time and end time
$start = new DateTime('09:00:00');
// add 1 second because last one is not included in the loop
$end = new DateTime('16:00:01');
$interval = new DateInterval('PT30M');
$period = new DatePeriod($start, $interval, $end);
$previous = '';
foreach ($period as $dt) {
$current = $dt->format("h:ia");
if (!empty($previous)) {
echo "<input name='time' type='radio' value='{$previous}|{$current}'>
{$previous}-{$current}<br/>";
}
$previous = $current;
}
the outcome of above loop is as following
09:00am-09:30am
09:30am-10:00am
10:00am-10:30am
10:30am-11:00am
11:00am-11:30am
11:30am-12:00pm
12:00pm-12:30pm
12:30pm-01:00pm
01:00pm-01:30pm
01:30pm-02:00pm
02:00pm-02:30pm
02:30pm-03:00pm
03:00pm-03:30pm
03:30pm-04:00pm
What i am trying to achieve is exclude some of the time mentioned below if it exist in another array $existing_time
which looks like this
[0] => Array
(
[start_time] => 2014-03-28T14:00:00+1100
[end_time] => 2014-03-28T14:30:00+1100
)
[1] => Array
(
[start_time] => 2014-03-28T15:00:00+1100
[end_time] => 2014-03-28T15:30:00+1100
)
)
I need help in how to go about doing this, any help will be appreciated
Upvotes: 1
Views: 79
Reputation: 219834
I just added the start times to an array and then check to see if the current start time is in that array. If so, we skip it.
<?php
$start = new DateTime('09:00:00');
$end = new DateTime('16:00:01'); // add 1 second because last one is not included in the loop
$interval = new DateInterval('PT30M');
$period = new DatePeriod($start, $interval, $end);
$existing_time = array(
array(
'start_time' => '2014-03-28T14:00:00+1100',
'end_time' => '2014-03-28T14:30:00+1100'
),
array(
'start_time' => '2014-03-28T15:00:00+1100',
'end_time' => '2014-03-28T15:30:00+1100'
)
);
$booked = array();
foreach ($existing_time as $ex) {
$dt = new DateTime($ex['start_time']);
$booked[] = $dt->format('h:ia');
}
$previous = '';
foreach ($period as $dt) {
$current = $dt->format("h:ia");
if (!empty($previous) && !in_array($previous, $booked)) {
echo "<input name='time' type='radio' value='{$previous}|{$current}'> {$previous}-{$current}<br/>";
}
$previous = $current;
}
Upvotes: 3