代码改变世界

递归

2016-12-15 11:04  归属感  阅读(122)  评论(0)    收藏  举报

<?php
header("Content-type: text/html; charset=utf-8");
include('./db_mysql.php');
    /**
     * 无限极分类 定义的方法
     */

    function getList($pid=0,&$arr=array(),$spac=0){
        $spac = $spac+4;
        $sql = 'SELECT * FROM recursion WHERE pid='.$pid;//One  查询pid等于0的资源型  形参默认传值为0
        $res = mysql_query($sql);//执行                            
        while ($new_res = mysql_fetch_assoc($res)) {     //Two  将资源型 做索引数组    循环
            $new_res['name']=str_repeat("&nbsp;",$spac).'|--'.$new_res['name'];  //Six  将名称循环  出来;
            $arr[]=$new_res;                             //Three 将资源型行循环出的数组  添到$arr 数组中,添加个形参
            getList($new_res['id'],$arr,$spac);            //Four   自己调用自己,形参将传送自己
        }
        return $arr;     //返回$arr数组;
    }

    /**
     * 展示的方法
     */
    function getShow($pid=0,$selected=1){
        $data = getList($pid);
        $str = '';
        $str.= "<select>";
        foreach ($data as $key => $val){
            $selectedStr = '';
            if($val['id']==$selected){
                $selectedStr = 'selected';
            }
            $str.= "<option {$selectedStr}>{$val['name']}</option>";
        }
        $str. "</select>";
        return $str;
    }
    echo getShow(0,3);

?>