0

我的网站将用于预订酒店和公园的日光躺椅。通常情况下,躺椅每天的费用是默认价格,但有时会有一个高峰价格(例如假日季节或周末)。所以我有一张桌子

special_prices
--------
start_date
end_date
price

我有一个搜索/计算器功能,允许用户输入他们想租用躺椅的开始日期和结束日期,计算器会计算出包括特价在内的总价。

每个躺椅都有自己的记录,所以我有一个数组中与特定躺椅关联的所有 special_price 记录,我想我应该遍历这些记录中的每一个,如果用户输入的天数介于 special_price 记录的日期之间,那么我需要计算需要多少天才能将增加的金额添加到其中。

我很难弄清楚这一点,因为我是 php 新手,实际上只是为了学习经验而这样做。不过,我已经摆弄它太久了:(

4

1 回答 1

0

这个问题通常由 SQL存储过程来解决。但是由于您将问题标记为 php,因此这是一个 php 答案:

// Let's imagine that $db is a PDO instance

// fetch all special prices
$stmt = $db->query('SELECT * FROM `special_prices`;');
$specialPrices = $stmt->fetchAll(PDO::FETCH_ASSOC);

// init datetime objects
$startDate = new \DateTime('16.05.2013');
$endDate = new \DateTime('08.06.2013');
$currentDate = clone $startDate;

// set default price and init result price (set it to 0)
$defaultPrice = 10;
$resultPrice = 0;

while ($currentDate <= $endDate)
{
    // init price the will be added to teh result as a default one
    $addPrice = $defaultPrice;

    foreach ($specialPrices as $specialPrice)
    {
        // temp special price DateTime objects to compare them with the current date
        $specialPriceStartDate = new \DateTime($specialPrice['start_date']);
        $specialPriceEndDate = new \DateTime($specialPrice['end_date']);

        if ($currentDate >= $specialPriceStartDate && $currentDate <= $specialPriceEndDate)
        {
            // If one of special dates matches with the current date, set its price as $addPrice
            $addPrice = $specialPrice['price'];
            break;
        }
    }

    // add price (default or special as calculated before) to the result
    $resultPrice += $addPrice;

    // get the next day
    $currentDate->modify('+1 day');
}

// here is the result
echo $resultPrice;
于 2013-07-18T12:37:56.153 回答