2013-07-18 2 views
0

내 사이트는 호텔과 공원에서 일광욕 장 예약을위한 것입니다. 일반적으로 일광욕 비용에는 하루에 기본 요금이 들지만 때로는 최고가 요금 (예 : 연휴 또는 주말)이 있습니다. 그래서 테이블php - 특별 가격이있는 일수 계산하기

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

이 그리고 사용자가 안락을 고용하고자 할 때의 시작 날짜와 종료 날짜를 입력 할 수있는 검색/계산기 기능이 있고 계산기를 포함하여 총 가격을 파악 특별 요금.

각 안거에는 고유 한 레코드가 있으므로 배열의 특정 안락에 관련된 모든 special_price 레코드가 있습니다.이 레코드 각각을 반복해야하며 사용자가 입력 한 요일이 special_price 레코드의 날짜 그러면 나는 어떻게해서 더 많은 양의 돈을 더 많이 필요로하는지 계산할 필요가 있습니다.

저는 PHP를 처음 접했을 때이 문제를 파악하는 데 어려움을 겪었습니다. 내가 너무 오래 지금은 비록 :(

답변

0

이 문제에 대한 그것으로 조롱했습니다은 일반적으로 SQL Stored Procedures 해결하지만 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;