我创建了一个接收当前页面ID的函数,根据该结果将显示两个.php文件或只显示一个.php文件。
以下是我写的。我是否以正确的方式接近了这一点?
<?php
function get_search_or_nav($page_id) {
if(isset($page_id)) {
$id = $page_id;
$pages = array('home', 'thank-you');
foreach($pages as $page){
if($page==$id)
$match = true;
}
if($match) {
include("dir/file_1.php");
include("dir/file_2.php");
}
elseif (!$match) {
include("dir/file_1.php");
}
}
}
?>
$pages
变量包含$page_id
数组,即{。{1}}
每个$pages = array('home', 'thank-you');
文件都有.php
,$page_id
有index.php
数组是匹配$page_id = "home";
的列表:
$page_id
电话会是:
$pages = array('home', 'thank-you');
任何帮助或建议都将不胜感激。
答案 0 :(得分:1)
我会这样做:
$id = $page_id;
$pages = array('home', 'thank-you');
$match = in_array($id, $pages);
迭代不是必需的
答案 1 :(得分:1)
不需要foreach
循环。 PHP具有内置函数来处理您想要的内容(in_array()
):我将您的函数更改为:
function get_search_or_nav($page_id) {
if (isset($page_id)) {
$id = $page_id;
$pages = array('home', 'thank-you');
// make sure file is in allowed array (meaning it exists)
if(in_array(id, $pages)) {
include("dir/file_1.php");
include("dir/file_2.php");
return true;
}
// no match, so include the other file
include("dir/file_1.php");
return false;
}
}
答案 2 :(得分:0)
您可以通过以下方式接近您的职能:
function get_search_or_nav($page_id) {
if(isset($page_id)) {
$pages = array('home', 'thank-you');
// You could do this with for loop
// but PHP offers in_array function that checks
// if the given value exists in an array or not
// if found returns true else false
$match = in_array($page_id, $pages);
// you are including this in either case
// so no need to repeat it twice in both conditions
include("dir/file_1.php");
// if match include file 2
if ($match) {
include("dir/file_2.php");
}
}
// you might want to throw Exception or log error here
// or just redirect to some 404 page or whatever is your requirement
}