2013-01-06 67 views
0

我正在製作每個團隊參加的運動(羽毛球)的搜索頁面:上午,下午,晚上。一週內可以有三次播放時間。因此,該表是這樣的:如何在PHP中查看時間

start_time = "08:00:00" 
start_time2 = "12:00:00" 
start_time 3 = "18:00:00" 

,或者如果球隊只起每週一次,該表是這樣的:

start_time = "08:00:00" 
start_time2 = "00:00:00" 
start_time3 = "00:00:00" 

現在我的查詢是這樣的:

if (isset($_REQUEST['time'])){ 
foreach ($time as $value){ //make day stay checked 2012/12/31 
    if ($value == "早上") $morning = "checked"; 
    if ($value == "下午") $afternoon = "checked"; 
    if ($value == "晚上") $evening = "checked"; 
} 
if ($morning == "checked" and $afternoon != "checked" and $evening != "checked"){ //only morning 
    $criteria .= "and (start_time < '12:00:00' or start_time2 < '12:00:00' or start_time3 < '12:00:00')"; 
}elseif ($morning == "checked" and $afternoon == "checked" and $evening != "checked"){ //morning + afternoon 
    $criteria .= "and (start_time < '18:00:00' or start_time2 < '18:00:00' or start_time3 < '18:00:00')"; 
}elseif ($morning == "checked" and $afternoon != "checked" and $evening == "checked"){ //morning + evening 
    $criteria .= "and ((start_time < '12:00:00' and start_time >= '18:00:00') or (start_tim2e < '12:00:00' and start_time2 >= '18:00:00') or (start_time3 < '12:00:00' and start_time3 >= '18:00:00'))"; 
}elseif ($morning != "checked" and $afternoon == "checked" and $evening != "checked"){ //afternoon 
    $criteria .= "and ((start_time >= '12:00:00' and start_time < '18:00:00') or (start_time2 >= '12:00:00' and start_time2 < '18:00:00') or (start_time3 >= '12:00:00' and start_time3 < '18:00:00'))"; 
}elseif ($morning != "checked" and $afternoon == "checked" and $evening == "checked"){ //afternoon + evening 
    $criteria .= "and (start_time >= '12:00:00' or start_time2 >= '12:00:00' or start_time3 >= '12:00:00')"; 
}elseif ($morning != "checked" and $afternoon != "checked" and $evening == "checked"){ //only evening 
    $criteria .= "and (start_time >= '18:00:00' or start_time2 >= '18:00:00' or start_time3 >= '18:00:00')"; 
} 

有兩個問題:

  1. 有沒有更好的方法來編寫更少的代碼,以便運行更快?
  2. 如何避免檢查start_time是否爲00:00:00?因爲如果我不跳過支票,如果我只想在早上搜索,那麼情況就會如此。由於早上的時間少於12:00:00,而00:00:00的時間少於12:00:00。

回答

0

你爲什麼要通過if ($value == "早上") $morning = "checked";?只需使用值來更改查詢。

if ($value == "早上"){ 
     $criteria .= "and (start_time < '12:00:00' or start_time2 < '12:00:00' or start_time3 < '12:00:00')"; 
    } 
    elseif ($value == "下午"){ 
     $criteria .= "and (start_time < '18:00:00' or start_time2 < '18:00:00' or start_time3 < '18:00:00')"; 
    } 
    elseif ($value == "value3"){ 
     $criteria .= "query3"; 
    } 

'如果' 可以替換如果u想 '開關' 的情況下

switch ($value) { 
    case 0: 
     $criteria .= "query1" 
     break; 
    case 1: 
     $criteria .= "query2" 
     break; 
    case 2: 
     $criteria .= "query3" 
     break; 
}