How to build unlimited level of menu through PHP and mysql

前端 未结 8 1490
心在旅途
心在旅途 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:25

    You need to use recursive functions for this. Technically, there's a few ways to do it, but recursion is really the best option here.

    Here's the basic gist of how it would work:

    function drawMenu ($listOfItems) {
        echo "
      "; foreach ($listOfItems as $item) { echo "
    • " . $item->name; if ($item->hasChildren()) { drawMenu($item->getChildren()); // here is the recursion } echo "
    • "; } echo "
    "; }

    The properties and methods of $item are just examples, and I'll leave it up to you to implement these however you need to, but I think it gets the message across.

提交回复
热议问题