Recursively menu build in php -


i have stored menu below.

id      label    link            parent   ------  -------  --------------  --------     10  home     http://cms.dev  10           11     http://about    11           12  history  http://history  11           13  mission  http://mission  11           14  contact  http://contact  14   

how can generate ul html menu recursively table unlimited item.

home   history   mission contact 

what recursive function? when function calls itself.

in case, items of every node looks recursive structure. yes, have tree , tree may bypass in recursive maner.

so, recursively. example, if have plain array $menu items:

$menu = [     [         'id' => 10,         'label' => 'home',         'link' => 'http://cms.dev',         'parent' => 10,     ],     [         'id' => 11,         'label' => 'about',         'link' => 'http://about',         'parent' => 11,     ],     [         'id' => 12,         'label' => 'history',         'link' => 'http://history',         'parent' => 11,     ],     [         'id' => 13,         'label' => 'mission',         'link' => 'http://mission',         'parent' => 11,     ],     [         'id' => 14,         'label' => 'contact',         'link' => 'http://contact',         'parent' => 14,     ], ]; 

you may use function menu output:

function echomenu(&$menu, $parentid = null) {     echo '<ul>';     foreach ($menu &$item) {         if ((!$parentid && $item['id'] == $item['parent'])              || ($item['parent'] == $parentid && $item['id'] != $item['parent'])) {             echo '<li>';             echo "<a href=\"${item['link']}\">${item['label']}</a>";              // here recursive call of echomenu()             echomenu($menu, $item['id']);              echo '</li>';         }     }     echo '</ul>'; }  echomenu($menu); 

and pay etantion more handy use 'parent' => null declarations root nodes. condition in recursive function more simple:

        if ($item['parent'] == $parentid) { 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

css - Make div keyboard-scrollable in jQuery Mobile? -

ruby on rails - Seeing duplicate requests handled with Unicorn -