Find if the passed times are in the range in a php array
$MyArr = array(
array('1', 'Morning', '09:00:00','10:30:00'),
array('2', 'Late Morning', '10:31:00','12:00:00'),
array('3', 'Lunch', '12:01:00','14:00:00'),
array('4', 'Afternoon', '14:01:00','16:00:00'),
array('5', 'Evening', '16:01:00','19:00:00'),
);
I would like to create a function to check something like this
if '14:00:00', '16:00:00' is passed and can be found in that array it should return the first 2 values i.e. 4 and Afternoon
Here's the Test scenario:
'09:10:00','10:30:00' -> pass (return '1', 'Morning' )
'12:00:00','14:30:00' -> Fail
'10:30:00','12:00:00' -> should also pass (yeah, i need to add 1 minute to start time if it doesnt开发者_如何学C fit) (return '2', ' Late Morning' )
'09:00:00','16:00:00' -> Fail
How can i write code for this?
I Think this is what you meant. I did a couple of different versions, but you can try them locally and see what they do (or take a look at the ideone working example)
<?php
header('Content-Type: text/plain');
$MyArr = array(
array('1', 'Morning', '09:00:00','10:30:00'),
array('2', 'Late Morning', '10:31:00','12:00:00'),
array('3', 'Lunch', '12:01:00','14:00:00'),
array('4', 'Afternoon', '14:01:00','16:00:00'),
array('5', 'Evening', '16:01:00','19:00:00'),
);
// first one, find array entries that fall between the time specified
function in_date_range($array, $start = '00:00:00',$end = '23:59:59')
{
$start = strtotime(date('Y-m-d '.$start));
$end = strtotime(date('Y-m-d '.$end));
$results = Array();
foreach ($array as $arr)
{
// check if $arr times fall within $start/$end
//if (strtotime(date('Y-m-d '.$arr[2])) >= $start && strtotime(date('Y-m-d '.$arr[3])) <= $end)
// check if $start/end fall within $arr times
if ($start >= strtotime(date('Y-m-d '.$arr[2])) && $end <= strtotime(date('Y-m-d '.$arr[3])))
$results[] = Array($arr[0],$arr[1]);
}
return $results;
}
// secon one, find array entries that surround the time supplied
function in_date_range2($array, $time = '12:00:00')
{
$time = strtotime(date('Y-m-d '.$time));
$results = Array();
foreach ($array as $arr)
{
if ($time >= strtotime(date('Y-m-d '.$arr[2])) && $time <= strtotime(date('Y-m-d '.$arr[3])))
$results[] = Array($arr[0],$arr[1]);
}
return $results;
}
print_r(in_date_range($MyArr,'14:00:00','16:00:00'));
print_r(in_date_range($MyArr,'09:00:00','12:00:00'));
echo "\r\n\r\n";
print_r(in_date_range2($MyArr,'14:00:00'));
print_r(in_date_range2($MyArr,'16:00:00'));
?>
EDIT
updated: See the comments in the in_date_range
function (regarding how it looks at the data).
精彩评论