How to build unlimited level of menu through PHP and mysql

前端 未结 8 1365
心在旅途
心在旅途 2020-11-29 01:05

Well, to build my menu my menu I use a db similar structure like this

  2  Services                  0
  3  Photo Gallery             0
  4  Home                         


        
相关标签:
8条回答
  • 2020-11-29 01:39

    With a database structure like yours, it is possible to build the whole HTML menu with a single query and without recursion.

    Yes - I will repeat:

    • ONE QUERY
    • NO RECURSION

    This is the approach I always use myself.

    Pasted the code here - fully functional:

    http://pastebin.com/GAFvSew4

    Jump to line 67 to see the interesting part ("get_menu_html").

    The main loop starts at line 85.

    There are five "customizable" HTML snippets:

    1. menu wrapper opening (line 83)
    2. menu wrapper closing (line 122)
    3. menu item with childs opening (line 100)
    4. menu item with childs closing (line 92)
    5. menu item without childs (line 113)

    (The code could be cleaner if I hadn't worried with tabulation.)

    SQL to create and populate sample database is available at the end of the script.

    You can try and let us know your thoughts.

    0 讨论(0)
  • 2020-11-29 01:42

    I would suggest that you look into pre-ordered tree traversal. There is an article on the issue at:

    Managing Hierarchical Data in MySQL

    Effectively, you take each page as a 'node'. Each node has a reference to it's parent. When you change the layout of the nodes (add a child, move nodes, etc), you recalculate a 'left' and 'right' value for each node (the article above explains this in great detail, with links to source code in php). What you end up with is the ability to very quickly determine if a given node is a direct or indirect child of any other node, as well as get all the child nodes of a given node.

    0 讨论(0)
提交回复
热议问题