2012-03-28 71 views
0

我有一個場景,用戶提交酒店預訂的開始和結束日期。數據庫在一年中有不同的(每日)價格。考慮到用戶的日期範圍,我想首先計算用戶範圍在數據庫每個範圍內的天數,然後再乘以該日期範圍的每日價格。PHP日期和日期計數

用戶日期:

03 Jun 2012 - 03 Jul 2012 

相關日期範圍從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 
     ) 

) 

正如你所看到的保留在第一範圍開始,跨越了第二範圍和第三範圍內結束。

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; 
} 

此代碼幾乎工作,除了一個事實,它需要預約($stop)作爲是DB範圍,而不是用戶的範圍的最後日期的結束,我想不通爲什麼!

+0

循環'$日期',所以它會計算,直到數據庫範圍的結尾 – safarov 2012-03-28 11:42:49

回答

2

你有沒有考慮過在SQL中做這一切?這應該工作:

SELECT 
    SUM(
    datediff(
     IF($dateTo>date_to,date_to,$dateTo), 
     IF($dateFrom<date_from,date_from,$dateFrom) 
    ) * price_per_day 
) as total_cost 
FROM ranges 
WHERE '$dateFrom'<=date_to 
    AND '$dateTo'>=date_from