Overflow社区首次发帖!
目前我正在开发一个项目,并已开始使用PHP来动态插入页面。
此时此刻我已经......
switch ($route) {
case 'step1':
include('./views/enrolment/mainstream/_step1.php');
include('./views/partials/_footer.php') ;
break;
case 'step2':
include('./views/enrolment/mainstream/_step2.php');
include('./views/partials/_footer.php') ;
break;
case 'step3':
include('./views/enrolment/mainstream/_step3.php');
include('./views/partials/_footer.php');
break;
case 'step4':
include('./views/enrolment/mainstream/_step4.php');
include('./views/partials/_footer.php');
break;
case 'step5':
include('./views/enrolment/mainstream/_step5.php');
include('./views/partials/_footer.php');
break;
case 'step6':
include('./views/enrolment/mainstream/_step6.php');
include('./views/partials/_footer.php');
break;
case 'step7':
include('./views/enrolment/mainstream/_step7.php');
include('./views/partials/_footer.php');
break;
这意味着看起来非常长并且通过for循环更好地实现,但是我是PHP的新手并且完全不确定我将如何实现这个想法。
我们也欢迎任何其他没有使用for循环的建议!
谢谢你们!
答案 0 :(得分:6)
您可以使用php的file_exists()fn
检查该文件是否存在if(file_exists('./views/enrolment/mainstream/_'.$routes.'.php')) {
include('./views/enrolment/mainstream/_'.$routes.'.php');
include('./views/partials/_footer.php') ;
}
处理其他部分以满足您的需要。
答案 1 :(得分:0)
也许这个简单的解决方案对你有好处:
include('./views/enrolment/mainstream/_'.$route.'.php');
include('./views/partials/_footer.php');
答案 2 :(得分:0)
大幅减少代码:
include('./views/enrolment/mainstream/_step' . $route . '.php');
include('./views/partials/_footer.php');
答案 3 :(得分:0)
为什么不使用$route
作为加载文件的变量?
include("./views/enrolment/mainstream/_{$route}.php");
include('./views/partials/_footer.php') ;
答案 4 :(得分:0)
就像@praveen所说:
include('./views/enrolment/mainstream/_'.$routes.'.php');
但是你要重复:
include('./views/partials/_footer.php');
对于每个查询,为什么不在页面中将其作为静态?
答案 5 :(得分:0)
最好检查$route
值
if (in_array($route, range(1, 7))){
include('./views/enrolment/mainstream/_'.$route.'.php');
include('./views/partials/_footer.php') ;
} else {
//...error code
}
答案 6 :(得分:-1)
怎么样
$i = 1;
$steps = 7;
for($i = 1; $i <= $steps; $i++) {
if($route === 'step' . $i) {
include('./views/enrolment/mainstream/_step' . $i . '.php');
include('./views/partials/_footer.php');
break;
}
}
答案 7 :(得分:-1)
for($i = 0; $i < 7; $i++){
if($route == "step" . $i){
include('./views/enrolment/mainstream/_step' .$i . '.php');
include('./views/partials/_footer.php');
break;
}
}