PHP日期和日期;数日

PHP日期和日期;数日,php,date,Php,Date,我有一个场景,用户提交一个酒店预订的开始和结束日期。该数据库在一年中的不同时期具有不同的(每日)价格。给定用户的日期范围,我想首先从数据库中计算用户范围在每个范围内的天数,然后乘以该日期范围的每日价格 用户日期: 03 Jun 2012 - 03 Jul 2012 相关日期范围从DB开始 Array ( [0] => stdClass Object ( [date_from] => 2012-04-09 [

我有一个场景,用户提交一个酒店预订的开始和结束日期。该数据库在一年中的不同时期具有不同的(每日)价格。给定用户的日期范围,我想首先从数据库中计算用户范围在每个范围内的天数,然后乘以该日期范围的每日价格

用户日期:

  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;
}
foreach($key=>d的日期)
{
$days=0;
$user_start=strottime($range['start']);
$user_stop=strotime($range['stop']);
$db\u start=strottime($d->date\u from);
$db\u stop=strotime($d->date\u to);
如果($user\u start>=$db\u start&&$user\u stop<$db\u stop)
{
$start=$range['start'];
$stop=$range['stop'];
}
elseif($user\u start$db\u start)
{
$start=$d->date\u from;
$stop=$d->date\u to;
}    
elseif($user\u start$db\u stop)
{
$start=$range['start'];
$stop=$d->date\u to;
}
$days=计算天数($start,$stop);
$price+=$days*$d->price;
}

这段代码几乎可以工作,除了它将预订结束(
$stop
)作为DB范围的最后日期,而不是用户范围,我不明白为什么

您是否考虑过使用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
选择
总数(
datediff(
如果($dateTo>date\u to,date\u to,$dateTo),

如果($dateFromYou循环
$dates
,那么它将一直计算到DB范围结束