[SPAGUETTI 代码警报]
你可以试试这个
<?php
$pages = array(
'index.php' => 'Home',
'about.php' => array('pageTitle' => 'About', 'subpages' => array(
'about1.php' => 'About subpage #1',
'about2.php' => 'About subpage #2',
'about3.php' => 'About subpage #3')),
'contact.php' => 'Contact',
'faq.php' => 'FAQ',
'tutorials.php' => 'Tutorials',
) ;
$currentPage = basename($_SERVER['REQUEST_URI']) ;
?>
<div id="menu">
<ul id="menuList">
<?php foreach ($pages as $filename => $value) {
if (is_array ($value)) {
$pageTitle = $value ['pageTitle'];
} else {
$pageTitle = $value;
}
if ($filename == $currentPage) {
$attr_current = ' class="current"';
} else {
$attr_current = '';
}
?>
<li<?php echo $attr_current; ?>><a href="<?php echo $filename; ?>"><?php echo $pageTitle ; ?></a>
<?php if (is_array ($value)) { ?>
<ul id="submenuList">
<?php foreach ($value ['subpages'] as $subfilename => $subpageTitle) { ?>
<li><a href="<?php echo $subfilename; ?>"><?php echo $subpageTitle ; ?></a></li>
<?php } ?>
</ul>
<?php } ?>
</li>
<?php } //foreach ?>
</ul>
</div>
正如你所看到的,它不是最干净的解决方案,所以如果我要做这样的事情,我会像这样编写上面的代码:
<?php
$pages = array(
'index.php' => 'Home',
'about.php' => array('pageTitle' => 'About', 'subpages' => array(
'about1.php' => 'About subpage #1',
'about2.php' => 'About subpage #2',
'about3.php' => 'About subpage #3')),
'contact.php' => 'Contact',
'faq.php' => 'FAQ',
'tutorials.php' => 'Tutorials',
) ;
$currentPage = basename($_SERVER['REQUEST_URI']) ;
?>
<div id="menu">
<ul id="menuList">
<?php foreach ($pages as $filename => $value):
$pageTitle = is_array ($value) ? $value ['pageTitle'] : $value;
$attr_current = $filename == $currentPage ? ' class="current"' : '';
?>
<li<?=$attr_current?>><a href="<?=$filename?>"><?=$pageTitle?></a>
<?php if (is_array ($value)): ?>
<ul id="submenuList">
<?php foreach ($value ['subpages'] as $subfilename => $subpageTitle): ?>
<li><a href="<?=$subfilename?>"><?=$subpageTitle?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
</li>
<?php endforeach; ?>
</ul>
</div>
也不是很整洁但是..
如果您想使用后者,请记住: