0

私のサイトは、ホテルや公園で 1 日あたりのサンラウンジャーを予約するためのものです。通常、ラウンジャーの料金は 1 日あたりの既定の料金ですが、ピーク料金が発生する場合もあります (ホリデー シーズンや週末など)。だから私はテーブルを持っています

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 に答える