Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate navigation from a multi-dimensional array

The question: How do I generate navigation, allowing for applying different classes to different sub-items, from a multi-dimensional array?

Here is how I was doing it before I had any need for multi-level navigation:

Home 
Pics 
About

and was generated by calling nav():

function nav(){       
    $links = array(
        "Home" => "home.php",
        "Pics" => "pics.php",
        "About" => "about.php"
    );

    $base = basename($_SERVER['PHP_SELF']);

    foreach($nav as $k => $v){
        echo buildLinks($k, $v, $base);
    }
}

Here is buildLinks():

function buildLinks($name, $page, $selected){
    if($selected == $page){
       $theLink = "<li class=\"selected\"><a href=\"$page\">$name</a></li>\n";
    } else {
       $thelink = "<li><a href=\"$page\">$name</a></li>\n";
    }

    return $thelink;
}

My question, again:

how would I achieve the following nav (and notice that the visible sub navigation elements are only present when on that specific page):

Home
    something1
    something2 
Pics 
About

and...

Home
Pics
    people
    places 
About

What I've tried

From looking at it it would seem that some iterator in the SPL would be a good fit for this but I'm not sure how to approach this. I have played around with RecursiveIteratorIterator but I'm not sure how to apply a different style to only the sub menu items and also how to only show these items if you are on the correct page.

I built this array to test with but don't know how to work with the submenu1 items individually:

$nav = array(
array(
"Home" => "home.php",
"submenu1" => array(
    "something1"=>"something1.php",
    "something2" => "something2.php")
),
array("Pics" => "pics.php"),
array("About" => "about.php")
);

The following will print out the lot in order but how do I apply, say a class name to the submenu1 items or only show them when the person is on, say, the "Home" page?

$iterator = new RecursiveIteratorIterator(new RecursiveArrayIterator($nav));

foreach($iterator as $key=>$value) {
    echo $key.' -- '.$value.'<br />';
}

And this gets me:

Home
something1
something2
Pics
About

But I have no way to apply classes to those sub items and no way to only display them conditionally because I don't see how to target just these elements.

like image 810
Lothar Avatar asked May 20 '10 20:05

Lothar


1 Answers

Don't reinvent the wheel, use Zend_Navigation and you will be happy.

like image 67
takeshin Avatar answered Oct 11 '22 23:10

takeshin