简体   繁体   中英

PHP dynamic navigation menu active styling

I want to create a dynamic menu in PHP and based on what page they are on the menu will have different styling. I have this but it's not how I want it to be :(

This is the array I have, containing info from the database

Array(

    [Home] => Array
        (
            [url] => Home
            [name] => Home
            [is_home] => 1
        )

    [About] => Array
        (
            [url] => About
            [name] => About
            [is_home] => 0
        )

    [Contact] => Array
        (
            [url] => Contact.php
            [name] => Contact
            [is_home] => 0
        )

)

This is what I currently have,

    if(isset($_GET["p"])) {
     if(in_array($page_name, $navigation[$page_name])) {
          $navigation[$page_name]["name"] = "<span>{$navigation[$page_name]["name"]}</span>";
     }
}
foreach ($navigation as $nav) {
     echo "<li><a href=\"" . strtolower($nav["url"]) . "\">{$nav["name"]}</a></li>";
}

This is how the page_name variable looks

$page_name = current(explode(".", ucfirst(strtolower($_GET["p"]))));

As you can see this inserts the span tags in the navigation menu name so this works but that's not how I want it to be. I want to add class="active" the the list item that is the current page. I just don't know how to do it

I hope you understand what I mean and sorry for any messy indentation that occurred when pasting the code in here.

//Edit

The fetch and array code

$mysql->query("SELECT `page_name`, `is_home` FROM `pages` ORDER BY `order` ASC");

        $navigation_items = array();
        while ($mysql->fetch($row)){
            $navigation_items[] = array(
                "url"   => $row["page_name"],
                "name"  => current(explode(".", $row["page_name"])),
                "is_home"  => $row["is_home"]
            );
        }

        return $navigation_items;

First of all the array you provided is reformatted which means you changed the indexes into page names which isn't necessary. This is how you can achieve what you want:

<?php
$menu = $Db->fetchAll("SELECT * FROM `menu`"); //or whatever method you're using to get data from the database.
$current = null;
if(isset($_GET['p'])) {
  $current = current(explode(".", ucfirst(strtolower($_GET["p"]))));
}
$navigation = '';
for($i=0;$i<count($menu);$i++) {
  $url = ucfirst(strtolower($menu[$i]['url']));
  if($current == $url)
    $class = ' class="active"';
  else
    $class = '';
  $name = '<span'.$class.'>'.$menu[$i]['name'].'</span>';
  $navigation .= "<li><a href='{$url}'>{$name}</a></li>";
}
?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM