0

我正在尝试制作一个经过深思熟虑的综合系统,以包含我今天开始的一个小型爱好项目的页面。

这是我目前的代码:

$page = get_uri(1);
if(!isset($page)){ $page = "Home"; }
$pages = array(
        "" => "home.php",
        "Home" => "home.php", 
        "Product" => "product.php",
        "category" => "category.php"
);
if(in_array($page, $pages) && file_exists(PAGE_DIR.$pages[$page])){
    include(PAGE_DIR.$pages[$page]);
} else {
    echo 'Uh oh. Four Oh Four, we failed to find the page you are looking for. :( <br />';
}

PAGE_DIR 被定义为= "/pages/"我托管页面文件的位置。我创建Home.php只是为了证明我的理论,并且get_uri(1)现在是一个空值,因为我试图让这个理论起作用。我确定问题出在某处file_exists,但无法确定问题出在哪里。

4

3 回答 3

2

in_array checks for the array value, not the key, which is what you want. Use if (isset($pages[$page]) && ...) instead.

Depending on your environment, the filenames may be case-sensitive. Create the file as home.php if you use lowercase filenames in your code.

于 2012-12-28T12:04:51.300 回答
0

使用array_key_exists而不是in_array()

现在您的代码将如下所示。

$page = get_uri(1);
if(!isset($page)){ $page = "Home"; }
$pages = array(
        "" => "home.php",
        "Home" => "home.php", 
        "Product" => "product.php",
        "category" => "category.php"
);
if(array_key_exists($page, $pages) && file_exists(PAGE_DIR.$pages[$page])){
    include(PAGE_DIR.$pages[$page]);
} else {
    echo 'Uh oh. Four Oh Four, we failed to find the page you are looking for. :( <br />';
}
于 2012-12-28T12:15:21.127 回答
0

看起来条件应该是:

if(array_key_exists($page, $pages)  etc

http://php.net/manual/en/function.array-key-exists.php

于 2012-12-28T12:10:15.993 回答