你可以寫一個if語句的每一個環節,但是這是一個更整潔的方法。
navbar.php
<?php
// using home as default, and not throwing a notice when $_GET['page'] isn't set
$page = (isset($_GET['page'])? $_GET['page'] : 'home');
// create an array of pages and their titles
$pages = array(
'home' => 'Home',
'about' => 'About',
// etc
);
// output each, checking for which is active
foreach ($pages as $pagestring => $text){
$active = ($pagestring == $page? ' class="active"' : '');
echo '<li' . $active . '><a href="?page=' . $pagestring . '">' . $text . '</a></li>';
}
?>
如果某些頁面出現的下拉列表(在問題未畫出)一點點更多的工作需要做......這個NB包裝整個事情與<ul>
它沒有按」 t似乎在你的navbar.php文件中。
$currentpage = (isset($_GET['page'])? $_GET['page'] : 'home');
$pages = array(
'home' => 'Home', // just use a string for a simple link
'about' => 'About',
'cute' => array(// use an array for a dropdown
'text' => 'Cute things',
'children' => array(
'kittens' => 'Kittens',
'puppies' => 'Puppies',
)
),
// etc, you can include children in children too
);
echo createLinksRecursive($pages, $currentpage);
function createLinksRecursive($array, $currentpage){
$return = '<ul>';
foreach ($array as $pagestring => $linkarray){
// we don't want to worry about whether it's a string or array more than once
if (!is_array($linkarray)) $linkarray = array('text' => $linkarray);
// check for active
$active = ($pagestring == $currentpage? ' class="active"' : '');
// add the li and anchor element
$return .= '<li' . $active . '>
<a href="?page=' . $pagestring . '">' . $linkarray['text'] . '</a>';
// add children if there are any using the same function
if (isset($linkarray['children'])){
$return .= createLinksRecursive($linkarray['children'], $currentpage);
}
// close that li
$return .= '</li>';
}
// close the ul and return
$return .= '</ul>';
return $return;
}
index.php中的$ _GET是必要的嗎?或者它是你的方法來實現你想要實現的目標 – Shehary
請使用開關而不是ifelseif叢林 – Popnoodles
'