PHP foreach 菜单包括
我正在开发一个网站,我正在尝试对我的标题进行 foreach 包含,其中包括我的导航菜单(此处的主要主题)。
我的导航菜单 header.php 文件中的代码如下:
<!-- topmenu -->
<div class="menu-header">
<div class="container">
<ul class="top menu">
<?php
$nav = array("Home","About","Portfolio","Products","Services","Contact");
foreach($nav as $item){
if($item == $title){
echo "<li class='current-menu-ancestor parent'><a href='$item.php'>$item</a></li>";
}else{
echo "<li><a href='$item.php'>$item</a></li>"; }
}
?>
</ul>
</div>
</div>
<!--/ topmenu -->
您可能会注意到代码中的条件是 if($item == $title)
。在我的 index.php 中,我包含了 $title="Home";
我打算在这个 if 语句中获取和使用它。
在我的 index.php 页面上,我已将其包含在以下代码中:
<?php
include("header.php");
$title = "Home";
?>
谁能告诉我哪里出错了?
Im developing a website and I am trying to a foreach include for my header which includes my navigation menu (the main topic here).
My code inside the header.php file for the navigation menu is here:
<!-- topmenu -->
<div class="menu-header">
<div class="container">
<ul class="top menu">
<?php
$nav = array("Home","About","Portfolio","Products","Services","Contact");
foreach($nav as $item){
if($item == $title){
echo "<li class='current-menu-ancestor parent'><a href='$item.php'>$item</a></li>";
}else{
echo "<li><a href='$item.php'>$item</a></li>"; }
}
?>
</ul>
</div>
</div>
<!--/ topmenu -->
You may notice that in the code is the condition if($item == $title)
. In my index.php I have included $title="Home";
which I intended to be taken and used in this if statement.
On my index.php page I have included this with the following code:
<?php
include("header.php");
$title = "Home";
?>
Can anyone tell me where I am going wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不是答案,但注释不适合格式化代码。您可能想要删除某些 HTML 的重复项:
如果您决定更改菜单结构中的某些内容并且仅更改菜单 html 的一个副本,那么像您那样复制 HTML 可能会导致以后出现维护问题。
Not an answer, but comments aren't suitable for formatted code. You might want to de-duplicate some of your HTML:
Duplicating HTML as you did can lead to maintenance problems later on, if you decide to change something in the menu structure and change only one of the copies of the menu html.
header.php 无法展望未来。如果您希望在包含中设置变量,则需要在之前设置它:
所以您基本上只是切换了行。
此外,我建议您在开发时启用最高级别的错误报告,因为它会向您发出有关键入代码时可能发生的常见错误的警告。
您可以通过将以下两行添加到脚本顶部来完成此操作:
或更改 PHP 配置。
header.php can not look into the future. If you want the variable to be set in the include, you need to set it before:
So you basically just switched the lines.
Additionally I suggest that you enable error reporting to the highest level when you develop, as it will give you warning on common mistakes that can happen while typing code.
You can do this by adding the following two lines to the top of your script:
or by changing your PHP configuration.
您需要在包含 header.php 之前设置 $title!
IE
You need to set $title before including header.php!
i.e.