且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

PHP动态下拉菜单

更新时间:2023-02-22 15:07:03

您需要编写一个递归函数来做到这一点,并让它自己调用.我尚未对此进行测试,但我认为它应该可以帮助您入门.我不会认可此函数的效率,因为它遍历数组中的每个项目并进行比较,即使您每次运行仅需要一个或两个项目(可能)也是如此.

You need to write a recursive function to do this and have it call itself. I haven't tested this out, but I think it should get you started. I wouldn't endorse this function's efficiency since it runs through every item in the array and does a comparison even though you're going to only need an item or two from each run (likely).

PHP:

$arr = array(...);
function output_lis($parentID = NULL){
    global $arr;
    $stack = array(); //create a stack for our <li>'s 
    foreach($arr as $a){ 
        $str = '';
            //if the item's parent matches the parentID we're outputting...
        if($a['parent']===$parentID){ 
            $str.='<li>'.$a['title'];

                    //Pass this item's ID to the function as a parent, 
                    //and it will output the children
            $subStr = output_lis($a['id']);
            if($subStr){
                $str.='<ul>'.$subStr.'</ul>';
            }

            $str.='</li>';
            $stack[] = $str;
        }
    }
    //If we have <li>'s return a string 
    if(count($stack)>0){
        return join("\n",$stack);
    }

    //If no <li>'s in the stack, return false 
    return false;
}

然后将其输出到您的页面上.像这样:

Then output this on your page. Something like:

<ul>
    <?php echo output_lis(); ?>
</ul>

这是我的示例数组:

$arr = array(
        array('title'=>'home','parent'=>NULL,'id'=>1), 
        array('title'=>'sub1','parent'=>1,'id'=>2), 
        array('title'=>'sub2','parent'=>1,'id'=>3), 
        array('title'=>'about us','parent'=>NULL,'id'=>4), 
        array('title'=>'sub3','parent'=>4,'id'=>5), 
        array('title'=>'sub4','parent'=>4,'id'=>6), 
    );