抱歉,这似乎是一个菜鸟问题.今天早上我的大脑无法工作.
我试图执行多个if语句,但它们表现不正常.它似乎总是在找到它正在寻找的模板之后加载最少的模板.做这样的事情的最佳方法是什么:
$post = $wp_query->post;
if ( in_category('7') ) {include(TEMPLATEPATH . '/post-experts.php');}
if ( in_category('6') ) {include(TEMPLATEPATH . '/post-radio.php');}
if ( in_category('5') ) {include(TEMPLATEPATH . '/post-lifestyle.php');}
else {include(TEMPLATEPATH . '/singleorigional.php');
}
Run Code Online (Sandbox Code Playgroud)
为了效率,你最好使用 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.
}
Run Code Online (Sandbox Code Playgroud)
编辑:我决定稍后再回到这个话题,以更好地解释为什么这更好。
if else 组合意味着一个顺序。例如
if(thingy == "thing1"){
//Do one thing
}
elseif(thingy == "thing2"){
//Do another thing
}
elseif(thingy == "thing3"){
//Do a different thing
}
else{
//Catch anything
}
Run Code Online (Sandbox Code Playgroud)
有了这个,这意味着它将检查第一个条件,如果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.
}
Run Code Online (Sandbox Code Playgroud)
相反,它的作用是首先获取答案,例如 thing == "thing3",然后它会跳过其他不相关的情况,而只做它需要做的事情。它不使用顺序,而是有点像指向正确答案。因此,您的实际答案是第一种情况还是第一种情况并不重要,它只会做相关的事情。
所以总结一下:如果您使用开关,并且您的回答案例是第 100 个案例,它将指出找到该开关(答案)后要做什么,如果您要使用 ifelse 并且您的答案是第 100 个变体ifelse,在做它需要做的事情之前,它必须遍历 99 个其他毫无意义的检查。
| 归档时间: |
|
| 查看次数: |
27215 次 |
| 最近记录: |