Using recursion to build navigation

后端 未结 2 1609
抹茶落季
抹茶落季 2020-12-15 01:35

I\'m building navigation for a site and for the life of me I can\'t figure out recursion. I have all my data stored via MySQL using this design:

2条回答
  •  余生分开走
    2020-12-15 02:11

    Here's an example with recursion.

    function buildNavigation($items, $parent = NULL)
    {
        $hasChildren = false;
        $outputHtml = '
      %s
    '; $childrenHtml = ''; foreach($items as $item) { if ($item['parent'] == $parent) { $hasChildren = true; $childrenHtml .= '
  • '.$item['category_name']; $childrenHtml .= buildNavigation($items, $item['category_id']); $childrenHtml .= '
  • '; } } // Without children, we do not need the
      tag. if (!$hasChildren) { $outputHtml = ''; } // Returns the HTML return sprintf($outputHtml, $childrenHtml); } print buildNavigation($items);

    That script produces the following output :

    • Menu 1
    • Menu 2
      • Sub Menu 2.1
      • Sub Menu 2.2
      • Sub Menu 2.3
        • Sub Menu 2.2.1
        • Sub Menu 2.2.2
        • Sub Menu 2.2.3
    • Menu 3

提交回复
热议问题