为提高效率,您最好使用 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
}
有了这个,这意味着它将检查第一个条件,如果thing == thing1,如果不是,则检查它是否等于下一个条件,即thing == thing2,依此类推。如果您通常总是期待thing1,那么这可能没问题,因为您只是在捕捉其他一些东西。但是,实际上在找到所需的解决方案之前检查所有可能的条件是低效的。
相反,通过编写等效的 switch 语句:
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.
}
相反,它的作用是首先获取答案,例如 thing == "thing3",然后它会跳过其他不相关的情况,而只做它需要做的事情。它不使用命令,而是有点像指向正确答案。因此,您的实际答案是第一种情况还是第一种情况并不重要,它只做相关的事情。
总结一下:如果您使用开关,并且您回答的案例是第 100 个案例,那么它将指出在找到该开关(答案)之后要做什么,如果您要使用 ifelse 并且您的答案是第 100 个变体ifelse,在做它需要做的事情之前,它必须遍历 99 个其他无意义的检查。