使用 PHP 导航栏和 else 是语句更新内容


updating content with php nav bar and else is statements

主页加载时出现一个错误,

注意:未定义的索引:CONTACT in/Applications/XAMPP/xamppfiles/htdocs/lpnew/index.php 第 5 行

没有任何链接保持活动状态,也不会切换内容。

索引页:

<?php $pg = 'index'; ?>
<?php include('includes/header.php'); ?>
<?php 
    $pg = $_GET[$pg];
    if ($pg == "services") {
        include("services.php");
    } elseif($pg == "employees") {
        include("employees.php");
    } elseif($pg == "contact") {
        include("contact.php");
    } else {
        include("home.php");
    };
?>
<?php include('includes/footer.php'); ?>

导航栏header.php

<?php
$pages = array(
    "index" => "HOME", 
    "services" => "SERVICES", 
    "employees" => "EMPLOYEES", 
    "contact" => "CONTACT"
); 
$pg = (isset($_GET['pg'])) ? $_GET['pg'] : "";
foreach ($pages as $url => $pg) {
    echo '<li ';
    if ($pg == $url) {
        echo '<li><a class=active href="index.php?p='
        . htmlspecialchars(urlencode($url)). '">' 
        . htmlspecialchars($pg) . '</a></li>';
    } else {
        echo '<li><a href="index.php?p=' . $url . '">' . $pg . '</a></li>';
    }
}
?>

这是你的问题:

$pg = (isset($_GET['pg'])) ? $_GET['pg'] : "";
foreach ($pages as $url => $pg) {

您正在重新定义$pg以便它解析为$pages的最后一个索引。此行正在尝试读取未定义的$_GET['CONTACT']

$pg = $_GET[$pg];
if ($pg == "services") {
    include("services.php");
} elseif($pg == "employees") {
    include("employees.php");
} elseif($pg == "contact") {
    include("contact.php");
} else {
    include("home.php");
};

正如 sverri 已经指出的那样,您所要做的就是更改循环的值部分:

foreach ($pages as $url => $val) {
    echo '<li ';
    if ($val == $url) {
        echo '<li><a class=active href="index.php?p='
        . htmlspecialchars(urlencode($url)). '">' 
        . htmlspecialchars($val) . '</a></li>';
    } else {
        echo '<li><a href="index.php?p=' . $url . '">' . $val . '</a></li>';
    }
}

正是因为这行:

<?php include('includes/header.php'); ?>

在其中,使用 $pg 作为保存值的变量遍历 $pages 数组:

foreach ($pages as $url => $pg) {
    // ...
}

这会用数组的最后一个值(在本例中为 'CONTACT')覆盖索引文件中定义的 $pg 的原始值

要解决此问题,您只需更改循环中变量的名称,如下所示:

foreach ($pages as $url => $someOtherName) {
    // ...
}