PHP/MySQL - building a nav menu hierarchy

前端 未结 5 552
予麋鹿
予麋鹿 2021-01-01 05:24

So the final menu will look something like this:

Item B
    Item B-1
        Item B-1-2
        Item B-1-1
Item A
    SubItem A-1
    SubItem A-2
Item C
         


        
5条回答
  •  离开以前
    2021-01-01 05:45

    Hierarchical data is somewhat annoying in a relationsal database (excluding Oracle, which has operators in START WITH/CONNECT BY to deal with this). There are basically two models: adjacency list and nested sets.

    You've chosen adjacency sets, which is what I typically do too. It's far easier to change than the nested set model, although the nested set model can be retrieved in the correct order in a single query. Adjacency lists can't be. You'll need to build an intermediate data structure (tree) and then convert that into a list.

    What I would do (and have done recently in fact) is:

    • select the entire menu contents in one query ordered by parent ID;
    • Build a tree of the menu structure using associative arrays or classes/objects;
    • Walk that tree to create nested unordered lists; and
    • Use a jQuery plug-in like Superfish to turn that list into a menu.

    You build something like this:

    $menu = array(
      array(
        'name' => 'Home',
        'url' => '/home',
      ),
      array(
        'name' => 'Account',
        'url' => '/account',
        'children' => array(
          'name' => 'Profile',
          'url' => '/account/profile',
        ),
      ),
      // etc
    );
    

    and convert it into this:

    The PHP for generating the menu array from is reasonably straightforward but a bit finnicky to solve. You use a recursive tree-walking function that builds the HTML nested list markup but will leave it's implementation as an exercise for the reader. :)

提交回复
热议问题