2013-06-02 93 views
0

我在PHP中有一個關聯數組。 下面是代碼:smarty中的多級菜單

$result = mysql_query("SELECT * FROM `tb_menu` ORDER BY id ASC"); 
$menu = array(); 
$menu_index = array(); 
while($row = mysql_fetch_assoc($result)){ 
    if($row['par'] == 0) { 
    $menu[] = $row; 
    $menu[sizeof($menu)-1]['child'] = array(); 
    $menu_index[$row['id']] = &$menu[sizeof($menu)-1]; 
    } else { 
    $menu_index[$row['par']]['child'][] = $row; 
    $menu_index[$row['id']] = &$menu_index[$row['par']]['child'][sizeof($menu_index[$row['par']]['child'])-1]; 
    } 
} 
/*print ('<pre>') ; 
     print_r ($menu) ; 
     print ('</pre>') ; exit();*/ 
$smarty->assign('menu', $menu); 

我不能讓它在Smarty的工作,因爲我在這一個初學者。 請幫我做出這樣的多級菜單

<ul> 
<li><a href="">first level</a> 
    <ul> 
     <li><a href="">second level</a></li> 
      ...................................... 
      <ul> 
        <li><a href="">N-level</a></li> 
      <ul> 
    </ul> 
</li> 
</ul> 
</li> 

感謝

回答

0

這裏有一個如何遍歷在最新版本的Smarty的一些多級陣列的例子:

<ul> 
    {foreach $menu as $first_level} 
    <li><a href="">first level</a></li> 
    {/foreach} 
    {if array_key_exists('child', $first_level)} 
    <ul> 
    {foreach $first_level['child'] as $second_level} 
     <li><a href="">second level</a></li> 
    {/foreach} 
    {if array_key_exists('child', $second_level)} 
    <ul> 
     {foreach $second_level['child'] as $n_level} 
     <li><a href="">N-level</a></li> 
     {/foreach} 
     <li><a href="">N-level</a></li> 
    </ul> 
    {/if} 
    </ul> 
    {/if} 
</ul> 

這不是遞歸的,所以這個假定你知道陣列的深度...

這裏是一個你可以用來做recursiv的模式的鏈接Ë模板:http://www.brain-dump.org/blog/entry/32

0
$menu= array(
        'about' => 'url', 
        'contact' => 'url', 
        'service' =>array(
             'service1' => 'url', 
             'service2' => 'url', 
             'service3' => 'url', 
             'service4' => 'url'), 
        'others'=>array(
            'other1' => 'url', 
            'other2' =>'url', 
            'other3' =>'url'), 
        'session'=>'url' 
        ); 

這一下我們可以遍歷這個多級陣列在我們Smarty3模板的示例

<ul > 
{foreach $menu as $value} 
    {if $value|is_array} 

     <li><a href="#" >{[email protected]}</a>       
     <ul> 
      {foreach $value as $subvalue} 

       <li><a href="#">{[email protected]}</a></li> 

      {/foreach} 
     </ul> 
     </li> 


    {else} 

    <li><a href="{$value}">{[email protected]|capitalize} </a></li> 

    {/if} 

{/foreach} 
</ul>