0

我在 PHP 中有一个关联数组。这是代码:

   $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>

谢谢

4

2 回答 2

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>

这不是递归的,因此假设您知道数组的深度...

这是您可以用来进行递归模板的模式的链接:http ://www.brain-dump.org/blog/entry/32

于 2013-07-30T22:19:12.890 回答
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="#" >{$value@key}</a>                        
         <ul>
            {foreach $value as $subvalue}

                <li><a href="#">{$subvalue@key}</a></li>

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


   {else}

   <li><a href="{$value}">{$value@key|capitalize} </a></li>

    {/if}

{/foreach}
</ul>
于 2014-04-14T20:48:38.933 回答