从多维数组生成导航

Lot*_*har 7 php navigation iterator

问题:如何生成导航,允许从多维数组中将不同的类应用于不同的子项?

在我需要多级导航之前,我就是这样做的:

Home 
Pics 
About
Run Code Online (Sandbox Code Playgroud)

并通过调用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);
    }
}
Run Code Online (Sandbox Code Playgroud)

这是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;
}
Run Code Online (Sandbox Code Playgroud)

我的问题,再次:

我将如何实现以下导航(并注意到可见的子导航元素仅在该特定页面上出现时):

Home
    something1
    something2 
Pics 
About
Run Code Online (Sandbox Code Playgroud)

和...

Home
Pics
    people
    places 
About
Run Code Online (Sandbox Code Playgroud)

我试过的

从它看来,SPL中的某些迭代器似乎很适合这个,但我不知道如何处理它.我玩过RecursiveIteratorIterator,但我不知道如何将不同的样式仅应用于子菜单项,以及如何在正确的页面上显示这些项目.

我构建了这个数组来测试,但不知道如何单独使用子菜单项:

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

以下将按顺序打印出该批次,但我如何申请,比如将一个类别名称应用于子菜单项目,或者仅在该人员开启时显示它们,例如"主页"页面?

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

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

这让我:

Home
something1
something2
Pics
About
Run Code Online (Sandbox Code Playgroud)

但我没有办法将类应用于这些子项,也没有办法只是有条件地显示它们,因为我看不到如何只针对这些元素.

Art*_*cto 1

您使用 RecursiveIteratorIterator 走在正确的轨道上。它本质上是扁平化递归迭代器。这是正确的方法:

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

$it = new RecursiveIteratorIterator(
    new RecursiveArrayIterator($nav),
    RecursiveIteratorIterator::SELF_FIRST
);

foreach ($it as $k => $v) {
    if ($it->getDepth() == 0)
        continue;
    echo str_repeat("    ", $it->getDepth() - 1) .
        "$k => $v\n";
}
Run Code Online (Sandbox Code Playgroud)

给出

Home => home.php
submenu1 => Array
    something1 => something1.php
    something2 => something2.php
Pics => pics.php
About => about.php
Run Code Online (Sandbox Code Playgroud)