从数据库中的ARRAY创建多级菜单

时间:2013-12-27 22:22:35

标签: php mysql mysqli

下面是两个函数,它们将处理来自MySQL数据库的查询和退出菜单。

此函数循环遍历数组。采用2个参数。

function loop_section($array, $parent_id = 0){
        echo '<ul>';
            foreach($array as $section){
                echo '<li>';
                echo $section->section_name;
                echo '</li>';
            }
        echo '</ul>';
    }

此功能处理从数据库中的表格部分查询菜单。

function fetch_sections(){
        global $db;
        $array = array();
        $query = $db->SELECT("SELECT * FROM sections");
        $array = $db->ROWS();
        loop_section($array);
    } 

这是我的问题,我将如何使用loop_section()函数中传递的数组来创建多级菜单?

这是数据库结构 Database Strucutre

2 个答案:

答案 0 :(得分:0)

未经测试,但尝试这样的事情:

function print_section(array $sections, $parent_id = null) {
    echo '<ul>';
    foreach($sections as $section) {
        if($section->parent_id != $parent_id)
            continue;
        echo '<li>';
        echo $section->section_name;
        print_section($sections, $section->section_id);
        echo '</li>';
    }
    echo '</ul>';
}

function fetch_sections(){
    global $db;
    $query = $db->SELECT("SELECT * FROM sections ORDER BY section_order"); // assuming that you have section_order column
    return $db->ROWS();
}

function print_sections() {
    print_section(fetch_sections());
}

答案 1 :(得分:0)

试试这个

$array_parent_id = array();

function fetch_sections($parent_id = null){
            global $db;
            $array = array();                       
            if($parent_id){
                    $query = $db->SELECT("SELECT * FROM sections where parent_id =".$parent_id);
                    $array_parent_id[] = $parent_id;            
            }else{
                $query = $db->SELECT("SELECT * FROM sections");

            }

                $array = $db->ROWS();
            loop_section($array);

        }

function loop_section($array, $parent_id = null){
            echo '<ul>';
                foreach($array as $section){
                                // check if parent_id of section into array $array_parent_id to pervent duplication             
                    if(in_array($section->parent_id,$array_parent_id)) continue;
                    echo '<li>';
                    echo $section->section_name;
                    if($section->parent_id != null){
                        fetch_sections($section->parent_id);                
                    }
                    echo '</li>';
                }
            echo '</ul>';
}