I have a scenario where a user submits a start and stop date for a reservation in a hotel. The database has different (daily) prices for periods of the year. Given the user’s date range I want to start by counting the number of days the user’s range has in each range from the database and then multiplying that by the daily price for that date range.
User’s dates:
03 Jun 2012 - 03 Jul 2012
Relevant date ranges from the DB
Array
(
[0] => stdClass Object
(
[date_from] => 2012-04-09
[date_to] => 2012-06-04
[price] => 44
)
[1] => stdClass Object
(
[date_from] => 2012-06-04
[date_to] => 2012-07-02
[price] => 52
)
[2] => stdClass Object
(
[date_from] => 2012-07-02
[date_to] => 2012-07-16
[price] => 61
)
)
As you can see the reservation begins in the first range, spans the second range and ends in the third range.
foreach ($dates as $key => $d)
{
$days = 0;
$user_start = strtotime($range['start']);
$user_stop = strtotime($range['stop']);
$db_start = strtotime($d->date_from);
$db_stop = strtotime($d->date_to);
if( $user_start >= $db_start && $user_stop < $db_stop )
{
$start = $range['start'];
$stop = $range['stop'];
}
elseif( $user_start <= $db_start && $user_stop > $db_start )
{
$start = $d->date_from;
$stop = $d->date_to;
}
elseif( $user_start <= $db_stop && $user_stop > $db_stop )
{
$start = $range['start'];
$stop = $d->date_to;
}
$days = calculate_nbr_days($start, $stop);
$price += $days * $d->price;
}
This code almost works, except for the fact it takes the end of the reservation ($stop) as being the last date of the DB range instead of the user’s range and I can’t figure out why!
Have you considered doing it all in SQL? Something this should work: