2012-06-08 2 views
1

나는 select 입력에서 일련의 옵션을 제공하는이 함수를 가지고있다. 옵션은 5 분 간격으로 시간을 알려줍니다. 문제는 시간이 23:45와 같을 때 옵션이 00:10부터 시작하여 $ j 변수를 기반으로 반복됩니다.PHP 시작 시간과 종료 시간 사이의 시간 루프

이것은 단어로하고 싶습니다. $ open_time에서 $ close_time까지 5 분 간격으로 옵션 목록을 제공하십시오. 현재 시간 ($ timeNow)이 $ open_time보다 큰 경우 $ open_time을 $ timeNow로 설정하여 첫 번째 옵션으로 표시합니다. 이 루프는 $ close_time까지만 수행하십시오.

분명히하는 것이 좋겠습니다.

function selectTimesofDay(){ 
    $output = ""; 
    $now = date('G:i ', time()); // time now 
    $timeNow = strtotime($now); // strtotime now 
    $next_five = ceil($timeNow/300) * 300; // get next 5 minute 
    // time now rounded to next 10 minute 
    $round5minNow = date('G:i', strtotime('+15 minutes',$next_five)); 
    $open_time = strtotime('17:00'); 
    $close_time = strtotime('23:59'); 

    // in the middle of working hours, time sets to current 
    if($timeNow >= $open_time && $timeNow < $close_time){ 
     $open_time = strtotime($round5minNow); 
    } 
    $time_diff = round(($close_time - $open_time)/60) ; 
    if(date('l') == 'Friday'){ 
     $j = ($time_diff/5)+11; // working hours extended untill 1:00 AM 
    } else{ 
     $j = ($time_diff/5)-1; // working hours untill 12:00 AM 
    } 

     for($i = 0; $i <= $j; $i++){ 
      $b = $i*5; 
      $data = date('l')." - ".date("H:i", strtotime('+'.$b.' minutes', $open_time)); 
      $output .= "<option value=\"{$data}\">";  
      $output .= $data; 
      $output .= "</option>"; 
     } 

    return $output; 
} 
+0

위 코드가 잘못된 이유는 무엇입니까? –

+0

클라이언트 컴퓨터의 시간이 23:45처럼되면 옵션 세트는 00:15부터 시작하여 23:55까지 계속됩니다! –

답변

7

당신이 정말 필요로하는 것은 : 당신의 도움 :) 여기

을 감사합니다 코드입니다

function selectTimesOfDay() { 
    $open_time = strtotime("17:00"); 
    $close_time = strtotime("23:59"); 
    $now = time(); 
    $output = ""; 
    for($i=$open_time; $i<$close_time; $i+=300) { 
     if($i < $now) continue; 
     $output .= "<option>".date("l - H:i",$i)."</option>"; 
    } 
    return $output; 
} 

그래서이 사이에 매 5 분 간격을 확인 루프를 실행하는 일 개폐. curent 시간 전이라면 건너 뛰고, 그렇지 않으면 옵션을 추가하십시오.

당신이하려고했던 것보다 훨씬 효율적이며 아마도 이해하기가 쉽습니다.

당신은 심지어 루프 후이를 넣을 수 있습니다 :

if($output == "") return "<option disabled>Sorry, we're closed for today</option>"; 

을 또한, 나는 항상 속성 value을 남겨 방법을 알 수 있습니다. value이없는 경우 옵션의 텍스트가 값으로 사용되기 때문입니다. 따라서이 솔루션은 불필요한 중복을 피합니다.

+0

+1 ['time()'] (http://br.php.net/manual/en/function.time.php). –

+0

감사합니다. Kolink. 그것은 훌륭합니다. 고맙습니다. –

2

하드 코드 된 열기 및 닫기 시간을 함수 본문 밖으로 가져 오는 것이 좋습니다. 함수를 사용하는 목표는 재사용 할 수있는 코드를 작성하는 것이므로 시간이 변경되면 함수로 변경하지 않고 전달되는 인수 만 변경할 수 있습니다.

// sample usage: print '<select>'.selectTimesofDay('17:00', '23:59').'</select>'; 
function selectTimesofDay($start=false, $end=false, $interval='5 minutes'){ 
    $interval = DateInterval::createFromDateString($interval); 
    $rounding_interval = $interval->i * 60; 
    $date = new DateTime(
     date('Y-m-d H:i', round(strtotime($start)/$rounding_interval) * $rounding_interval) 
    ); 
    $end = new DateTime(
     date('Y-m-d H:i', round(strtotime($end)/$rounding_interval) * $rounding_interval) 
    ); 

    $opts = array(); 
    while ($date < $end) { 
     if ($date->getTimestamp() < time()) { 
      $date->add($interval); 
      continue; 
     } 
     $data = $date->format('l').' - '.$date->format('H:i'); 
     //$opts[] = '<option value="'.$date->getTimestamp().'">'.$data.'</option>'; // < -- pass the timestamp instead of a string? 
     $opts[] = '<option>'.$data.'</option>'; 
     $date->add($interval); 
    } 

    return count($opts) < 1 ? 
     '<option value="-1">- closed -</option>' : 
     implode("\n", $opts); 
} 

문서

PHP의 DateTime 개체 - http://www.php.net/manual/en/class.datetime.php

PHP의 DateInterval 개체 - http://www.php.net/manual/en/dateinterval.format.php

PHP 함수 - http://www.php.net/manual/en/functions.user-defined.php

PHP 함수 튜토리얼 - http://www.tizag.com/phpT/phpfunctions.php

+0

Chris에게 감사드립니다. 이것은 훌륭한 해결책이기도합니다. 건배. –

관련 문제