0

我为导航菜单使用了以下 PHP 开关:

<?php include("header.php"); 
    if (! isset($_GET['page']))
    {
        include('./home.php');

    } else {    
        $page = $_GET['page'];  
        switch($page)
        {
            case 'about':
                include('./about.php');
                break;  
            case 'services':
                include('./services.php');
                break;  
            case 'gallery':
                include('./gallery.php');
                break;      
            case 'photos':
                include('./photos.php');
                break;  
            case 'events':
                include('./events.php');
                break;  
            case 'contact':
                include('./contact.php');
                break;
        }
    }
    include("footer.php"); 
    ?>

当我转到“照片”部分时,我将在照片中为其他画廊创建一个子列表。

当我现在在一个页面上时,我的 url 看起来像这样:

index.php?page=photos

我想知道我需要添加什么 PHP 代码,所以当我转到 CARS 部分时,我的 url 看起来像这样:

index.php?page=photos&section=cars

?

4

2 回答 2

3

我会采取以下方法。它允许您拥有文件的任意路径,并且恕我直言,它使扩展和阅读变得更简单。

<?php
    include("header.php"); 

    $page = isset($_GET['page']) ? trim(strtolower($_GET['page']))       : "home";

    $allowedPages = array(
        'home'     => './home.php',
        'about'    => './about.php',
        'services' => './services.php',
        'gallery'  => './gallery.php',
        'photos'   => './photos.php',
        'events'   => './events.php',
        'contact'  => './contact.php'
    );

    include( isset($allowedPages[$page]) ? $allowedPages[$page] : $allowedPages["home"] );

    include("footer.php"); 
?>

同样的想法可以在您的photos.php包含(或任何其他文件)中扩展,以处理您可能拥有的不同部分:

照片.php

<?php
    $section = isset($_GET['section']) ? trim(strtolower($_GET['section'])) : "members";

    $allowedPages = array(
        'members' => './photos/members.php',
        'cars'    => './photos/cars.php'
    );

    include( isset($allowedPages[$section]) ? $allowedPages[$section] : $allowedPages["members"] );
?>
于 2010-02-14T08:23:53.347 回答
1

从概念上讲,您不会只添加另一个嵌套级别的 switch 或 if/then 测试吗?

这可能会卡在您现有的开关中,但将其放入函数中可能更具可读性

case: 'photos'
  $section = photo_switch( $_GET['section'] );
  include( $section );
  break;

或者您可以只清理用户输入并使用它:

case 'photos'
  $section = preg_replace( "/\W/", "", $_GET['section'] );
  include( './photos/' . $section . '.php' );
  break
于 2010-02-13T04:57:14.947 回答