我正在尝试使用以下代码建立活动页面链接。但是随着将来我添加更多页面,如果还有更多的话。有没有办法缩短它?
<?php
$urlarray=explode('/', $_SERVER["REQUEST_URI"]);
$pageActive = end($urlarray);
$dashClass ='';
$userClass = '';
$settingClass = '';
$activePage = array(
"dashboard",
"settings",
"users"
);
if(in_array($pageActive, $activePage)) {
if($pageActive == 'users'){
$userClass = 'class="active"';
}else if($pageActive == 'dashboard'){
$dashClass = 'class="active"';
}else if($pageActive == 'settings'){
$settingClass = 'class="active"';
}
...
...
...
}
?>
在此处回显html
<ul>
<li <?php echo $dashClass;?>></li>
<li <?php echo $userClass;?>></li>
<li <?php echo $settingClass;?>></li>
</ul>
答案 0 :(得分:2)
使用switch
switch($pageActive) {
// Users
case 'users':
$userClass = 'class="active"'
break;
// Dash
case 'dashboard':
$dashClass = 'class="active"'
break;
//something else
case 'something-else':
$somethingElseClass = 'class="blah"'
break;
// Default fallback one
default:
$userClass = 'class="active"';
break;
}
编辑 您可以做
<li <?php if($pageActive === 'user'){ echo 'class="active"'; } ?>User</li>
<li <?php if($pageActive === 'dashboard'){ echo 'class="active"'; } ?>>Dashboard</li>
答案 1 :(得分:0)
它们已经是一个包含菜单项列表的数组,名称为“ activePage”。您可以尝试以下代码。
<?php
$urlarray=explode('/', $_SERVER["REQUEST_URI"]);
$pageActive = end($urlarray);
$activePage = array('dashboard', 'settings', 'users');
?>
<ul>
<?php
foreach($activePage as $_key => $_value) {
$menuSelect = '';
if( in_array($pageActive, $activePage) ) {
$menuSelect = 'class="active"';
}
?><li <?php echo $menuSelect; ?>><?php echo $_value; ?></li><?php
}
?>
</ul>