爲了提高效率,你最好使用switch語句,並那麼爲了抓住你在案件中沒有找到的那些人,你可以使用默認值。
switch(in_category){ //Begin switch statement.
case '7': //Check if it equals 7
include(TEMPLATEPATH . '/post-experts.php'); //Include our PHP code
break; //End this current condition.
case '6': //Check if it equals 6
include(TEMPLATEPATH . '/post-radio.php'); //Include our PHP code
break; //End this current condition.
case '5': //Check if it equals 5
include(TEMPLATEPATH . '/post-lifestyle.php'); //Include our PHP code
break; //End this current condition.
default: //If none of the above cases are found, do this.
include(TEMPLATEPATH . '/singleorigional.php'); //Include our PHP code
break; //End this current condition.
}
編輯:我決定在以後的日子回到這個,以便更好地解釋爲什麼這是更好的。
一個if else組合意味着一個順序。例如。
if(thingy == "thing1"){
//Do one thing
}
elseif(thingy == "thing2"){
//Do another thing
}
elseif(thingy == "thing3"){
//Do a different thing
}
else{
//Catch anything
}
有了這個,這意味着它會檢查第一個條件,如果事情== thing1,如果沒有,檢查它是否等於下一個條件是事== thing2等。如果你通常總是期待着事物1,那麼這可能是好的,因爲你只是在捕捉其他一些東西。但是,實際上,在達到所需的解決方案之前,檢查所有可能的條件是無效的。
相反,通過寫等效開關語句:
switch(thingy){
case "thing1":
//Do one thing
break;
case "thing2":
//Do another thing
break;
case "thing3":
//Do a different thing
break;
default:
//Catch anything
break; //Break is not needed if default is the final case.
}
這裏做的事情,而不是,是先搶了答案,例如東西==「thing3」,然後它會跳過其他不相關的情況,而只是做它需要做的事情。它不使用訂單,而是它有點像指向正確的答案。所以,如果你的實際答案是第一種情況,或者是第一種情況,它只會做相關的事。所以總結一下:如果你使用一個開關,並且你的答案是百分之一的情況下,它會指出發現開關(答案)後要做什麼,如果你使用ifelse,而你的答案是這個錯誤的第100個變體,它必須在做它需要做的事情之前迭代99次其他無意義的檢查。
什麼行爲不正確?你這樣做的方式對我來說似乎很好。 – Travesty3 2012-04-27 14:06:15
嗯......正是這樣?這個例子究竟是不是工作? – 2012-04-27 14:06:43
你可能想使用elseif? – Sgoettschkes 2012-04-27 14:07:02