2013-02-21 68 views
0

嘗試使用多維數組和遞歸構建導航。我有以下代碼:多維導航陣列

首先,我的文檔類型下的每個單獨的頁上運行<?php $title = 'pagename'; ?>(用於有源類檢測)

ARRAY:

<?php 

$nav_array = array ('Home' => 'index.php', 
        'About' => array ('about.php', array (
         'Michael' => array('michael.php', array (
          'Blog' => 'blog.php', 
          'Portfolio' => 'portfolio.php')), 
         'Aaron' => 'aaron.php' , 
         'Kenny' => 'kenny.php', 
         'David'=> 'david.php')), 

        'Services' => array ('services.php', array (
         'Get Noticed' => 'getnoticed.php', 
         'Hosting' => 'hosting.php')), 

        'Clients' => 'clients.php', 
        'Contact Us' => 'contact.php' 
    ); 

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

FOREACH:(產生NAV)

<ul> 
<?php 

foreach ($nav_array as $k => $v) { 
    echo buildLinks ($k, $v, $base);  
} 
?> 
</ul> 

b uildLinks:

<?php // Building the links 

function buildLinks ($label_name, $file_name, $active_class) { 
    if ($label_name == $title) { 
     $theLink = "<li><a class=\"selected\" href=\"$file_name\">$label_name</a></li>\n"; 
    } else { 
     $theLink = "<li><a href=\"$file_name\">$label_name</a></li>\n"; 
    } 

    return $theLink; 
} 


?> 

結果:http://khill.mhostiuckproductions.com/siteLSSBoilerPlate/arraytest.php

子菜單的會出現在父元素的使用CSS懸停。我需要能夠通過多個子級別而不用修改除陣列之外的任何內容。

如何使我的foreach以遞歸方式落在數組的其餘部分?

(注:我有一類的積極應用到當前頁面的能力,而類箭頭到具有一個子菜單當前父元素。)

回答

1

不管你用什麼數據結構來建立自己的導航,你需要讓你的函數的遞歸,這裏有一個快速和骯髒的方式:

echo "<ul>"; 
foreach ($nav_array as $nav_title => $nav_data) { 
    echo buildLinks($nav_title, $nav_data, $base, $title); 
} 
echo "</ul>"; 

/* NOTE that we pass $title to the function */ 
function buildLinks ($label_name, $file_name, $active_class, $title) { 

    $theLink = ''; 
    /* this is dirty code, you should reconsider your data structure */ 
    $navigation_list = false; 
    if (is_array($file_name)) { 
    $navigation_list = $file_name[1]; 
    $file_name = $file_name[0]; 
    } 

    if ($active_class == $title) { 
    $theLink = "<li><a class=\"selected\" href=\"$file_name\">$label_name</a></li>\n"; 
    } else { 
    $theLink = "<li><a href=\"$file_name\">$label_name</a></li>\n"; 
    } 

    if ($navigation_list) { 
    $theLink .= "<ul>"; 
    foreach ($navigation_list as $nav_title => $nav_data) { 
     $theLink .= buildLinks($nav_title, $nav_data, $active_class, $title); 
    } 
    $theLink .= "</ul>"; 
    } 

    return $theLink; 
} 

無論如何也不能一個乾淨的解決方案,如果我是你會改變數據結構,使其更容易處理。

+0

數據結構是指數組的結構?你有什麼建議,我應該採取什麼方式?我可以搜索的東西? – Michael 2013-02-21 22:00:00

+0

當然可以看到:http://stackoverflow.com/questions/11907790/recursive-function-for-dynamic-multilevel-menu-php – nubeiro 2013-02-22 11:28:53

0

我覺得這是一個非常糟糕的方式。我建議將菜單元素保存爲XML或JSON並使用解析器。它會方便你的工作。