使用嵌套链接URL构建嵌套菜单

时间:2015-12-06 12:38:17

标签: php mysql tree nested-loops

我已经阅读了关于树状菜单的以下链接,它提供了一个很好的解决方案,但链接不是嵌套的

https://stackoverflow.com/a/4495016/3754884

我想编辑此代码以更改嵌套链接网址:

 function get_menu_html( $root_id = 0 )
 {
$this->html  = array();
$this->items = $this->get_menu_items();

foreach ( $this->items as $item )
    $children[$item['parent_id']][] = $item;

// loop will be false if the root has no children (i.e., an empty menu!)
$loop = !empty( $children[$root_id] );

// initializing $parent as the root
$parent = $root_id;
$parent_stack = array();

// HTML wrapper for the menu (open)
$this->html[] = '<ul>';

while ( $loop && ( ( $option = each( $children[$parent] ) ) || ( $parent > $root_id ) ) )
{
    if ( $option === false )
    {
        $parent = array_pop( $parent_stack );

        // HTML for menu item containing childrens (close)
        $this->html[] = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 ) . '</ul>';
        $this->html[] = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 ) . '</li>';
    }
    elseif ( !empty( $children[$option['value']['id']] ) )
    {
        $tab = str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 );

        // HTML for menu item containing childrens (open)
        $this->html[] = sprintf(
            '%1$s<li><a href="%2$s">%3$s</a>',
            $tab,   // %1$s = tabulation
            $option['value']['link'],   // %2$s = link (URL)
            $option['value']['title']   // %3$s = title
        ); 
        $this->html[] = $tab . "\t" . '<ul class="submenu">';

        array_push( $parent_stack, $option['value']['parent_id'] );
        $parent = $option['value']['id'];
    }
    else
        // HTML for menu item with no children (aka "leaf") 
        $this->html[] = sprintf(
            '%1$s<li><a href="%2$s">%3$s</a></li>',
            str_repeat( "\t", ( count( $parent_stack ) + 1 ) * 2 - 1 ),   // %1$s = tabulation
            $option['value']['link'],   // %2$s = link (URL)
            $option['value']['title']   // %3$s = title
        );
}

// HTML wrapper for the menu (close)
$this->html[] = '</ul>';

return implode( "\r\n", $this->html );
}
}

代码输出如下:

 <ul>
   <li><a href="/1.html">1</a>
    <ul class="submenu">
    <li><a href="2.html">2</a>
        <ul class="submenu">
            <li><a href="3.html">3</a>
                <ul class="submenu">
                        <li><a href="4.html">4</a></li>
                    </ul>
            </li>
        </ul>
    </li>
</ul>

我想要这样的事情:

<ul>
   <li><a href="link1">Link1</a>
   <ul>
     <li><a href="link1/link2">Link2</a>
    <ul>
     <li><a href="link1/link2/link3">Link3</a></li>
      </ul>  
   </li>
    </ul>
  </li>
  <li><a href="link4">Link4</a></li>
</ul>

非常感谢您的帮助

0 个答案:

没有答案