获取switch语句中的案例列表

时间:2011-07-30 16:47:12

标签: php dynamic switch-statement

我使用PHP Switch语句来确定我网站的页面。所以这是一个例子:

switch($page) {
    case "about":
        $title_name = "About Us";
        $page_content = "includes/about-us.php";
        include("inner.php");
    break;
    case "services":
        $title_name = "Services";
        $page_content = "includes/services.php";
        include("inner.php");
    break;
}

我的文件结构是 index.php?page = about ,它使用htaccess转换为 / about /

我想要做的是将所有页面放在该switch语句中并自动获取并将其放入列表中,这样我就可以自动将其写入我的页脚页面,在那里我将拥有所有链接。

因此,不要手动输入页脚中的所有链接,如: Home |关于我们|服务|常见问题,它会根据我在Switch语句中提供的页面自动提取它。

有办法做到这一点吗?自动添加新页面也会很好,它会为新页面添加新案例,并自动在includes文件夹中创建页面。

如果有人能指出我正确的方向,我会非常感激。根据我的理解,我不相信你可以用switch语句来做这件事,我必须以我调用页面的方式重新工作,对吗?

4 个答案:

答案 0 :(得分:8)

$pages = array('about'=> 'About Us', 'services' => 'Services');

if (array_key_exists($page, $pages)) {
   $title_name = $pages[$page];
   $page_content = "includes/$page.php";
   include('inner.php');
}

对于您的页脚,您可以遍历页面列表。要添加新页面,只需将其添加到阵列并创建相应的文件。

但要回答你的问题:不,你不能在运行时分析代码语句。

答案 1 :(得分:5)

不,使用switch是不可能的 - 但您可以将这些信息存储在数组中:

$page_list = array(
    'about' => array(
        'title' => 'About Us',
        'content' => 'includes/about-us.php',
    ),
    'services' => array(
        'title' => 'Services',
        'content' => 'includes/services.php',
    ),
);

if(isset($page_list[$page])) {
    $page_info = $page_list[$page];

    $title_name = $page_info['title'];
    $page_content = $page_info['content'];

    include("inner.php");
} else {
    // 404 - file not found
}

// create links
foreach($page_list as $link_name => $page_ent) {
    echo "<a href=\"/{$link_name}/\">{$page_ent['title']}</a><br />"
}

// output
// <a href="/about/">About Us</a><br />
// <a href="/services/">Services</a><br />

答案 2 :(得分:0)

你有这种倒退。你想要的是拥有一个页面数组,然后为switch语句循环一次,为footer循环一次。或者,更好的是,完全摆脱switch语句,而是使用关联数组映射页面到构建特定页面可能需要的信息(交换机之间有很多常见的行为,所以知道你的页面是什么,你可能只是从那个构建正确的URL /。)。

答案 3 :(得分:0)

您无法从switch语句中获取所有值,您必须重新设计代码。当然有很多方法可以实现这一点,但我通常会做类似下面的事情,它比你的方法更短,更容易扩展。

<?php

$pages = array('home', 'about', 'services', 'faq');
$titles = array('Home', 'About us', 'Services', 'FAQ');

$index = array_search($_POST['p'], $pages);
if ($index !== false) {
   $page_content = 'includes/' . $pages[$index] . '.php';
   $title_name = $titles[$index];
} else {
   print 'Page not found';
}

?>

希望这会有所帮助。