Search code examples
phparrayscodeigniterrecursionhierarchy

how to make a recursive loop for a hierarchal navigation using Php Codeigniter?


here is my table and I need to display it using php?

Ex. Navigation Table enter image description here

And look like this:

enter image description here

Is there any php code for this?

Thanks!


Solution

  • Code in your model

    public function getHierMenu() {
        $rows = $this->db->get('table_name')->result();
    
        $depthIndex = array('nav_hier_root','nav_hier_d1','nav_hier_d2','nav_hier_d3','nav_hier_d4');
        $menu = [];
        foreach($rows as $row){
            $depth = $row->nav_hier_depth;
    
            if($depth > 0)
            $menu[$row->$depthIndex[0]] = [];
            if($depth > 1)
            $menu[$row->$depthIndex[0]][] = $row->$depthIndex[1];
            if($depth > 2)
            $menu[$row->$depthIndex[0]][$row->$depthIndex[1]][] = $row->$depthIndex[2];
            if($depth > 3)
            $menu[$row->$depthIndex[0]][$row->$depthIndex[1]][$row->$depthIndex[2]][] = $row->$depthIndex[3];
            if($depth > 4)
            $menu[$row->$depthIndex[0]][$row->$depthIndex[1]][$row->$depthIndex[2]][$row->$depthIndex[3]][] = $row->$depthIndex[4];
        }
    
        return $menu;
    }
    

    UPDATE

    Use this recursive function and pass the returned array ($menu) from the previous function to print the menu using ul li.

    function printMenu($menu) {
    
        echo '<ul>';
        foreach ($menu as $k => $v) {
            echo '<li>';
            if (!empty($v) && is_array($v)) {
                echo $k;
                printMenu($v);
            } else {
                echo $v;
            }
            echo '</li>';
        }
        echo '</ul>';
    }
    

    It's tested and working fine.