PHP: nested menu with a recursive function, expand only some nodes (not all the tree)

后端 未结 2 1085
半阙折子戏
半阙折子戏 2020-12-11 11:31

I have this array, called $nested (it\'s a long one, but I tried to get a comprehensive scenario):

Array
(
    [1] => Array
        (
                


        
相关标签:
2条回答
  • 2020-12-11 12:05

    At last that's what I did, it works very fine:

    // create array of ancestors' ID from current page
    function path($page = 0) {
        global $database_connApp, $connApp;
        // let's create arrays
        do {
            mysql_select_db($database_connApp, $connApp);
            $query_rsPage = "SELECT pages.pag_id FROM pages WHERE pages.pag_id = " . $page;
            $rsPage = mysql_query($query_rsPage, $connApp) or die(mysql_error());
            $row_rsPage = mysql_fetch_assoc($rsPage);
            $bid[] = $row_rsPage['pag_id'];
            $page = $row_rsPage['pag_parent'];
        } while ($page > 0);
    
        // move to the last array index
        end($bid);
        $output = $bid;
        return $output;
    }
    

    // create the menu
    function fmenu($parent, $array, $path) {
        $has_children = false;
        foreach($array as $key => $value) {
            if (in_array($value['parent'], $path)) {
                if ($value['parent'] == $parent) {
                    if ($has_children === false && $parent) {
                        $has_children = true;
                        echo '<ul>' ."\n";
                    }
                    $active = ($_GET['iData'] == $value['id']) ? ' class="active"' : '';
                    echo '<li' . $active . '>' . "\n";
                        echo '<a href="../pagine/' . $value['id'] . '/' . slugify($value['title']) . '.htm">' . html($value['title']) . '</a>' . " \n";
                    echo "\n";
                        fmenu($key, $array, $path);
                    echo "</li>\n";
                }
            }
        }
        if ($has_children === true && $parent) echo "</ul>\n";
    }
    

    echo fmenu(0, $nested, path($row_rsEdit['pag_id']));
    
    0 讨论(0)
  • 2020-12-11 12:08

    You're almost there. Just one small problem: instead of recursive($key, $array) you need recursive($key + 1, $array). Still, as said by others, this would be a lot nicer if you just generated the entire output with PHP and then controlled it all with javascript. Having the page reload every time the user clicks an item is really not a good user experience.

    0 讨论(0)
提交回复
热议问题