php递归

    public function tree()
    {
        //这个表示那拿到的数据库里面的内容
        $product=$this->order('catorder','asc')->select();
        return  $this->getTree($product);

    }
    //无限极递归
    public function getTree($data,$pid=0,$level=0){
        static $arr=array();
        foreach($data as $key=>$value){
            if($value['pid'] == $pid){
                $value['level']=$level;     //用来作为在模版进行层级的区分
                $arr[] = $value;            //把内容存进去
                $this->getTree($data,$value['id'],$level+1);    //回调进行无线递归
            }
        }
        return $arr;
    }
function recursionTree($arr,$pid)
{ 
    $list = array();
    foreach($arr as $val){ 
        if($val['pid'] == $pid){ 
            $tmp = recursionTree($arr,$val['id']);
            if($tmp){ 
                $val['son'] = $tmp;
            }
            $list[] = $val;
        }
    }
    return $list;
}


$arr = [
    ['id'=>1,'pid'=>0,'name'=>'1-1'],
    ['id'=>2,'pid'=>1,'name'=>'1-1-2'],
    ['id'=>3,'pid'=>2,'name'=>'1-1-2-3'],
    ['id'=>4,'pid'=>0,'name'=>'1-4'],
    ['id'=>5,'pid'=>4,'name'=>'1-4-5'],
    ['id'=>6,'pid'=>0,'name'=>'1-6'],
];

$tmp = recursionTree($arr,0);
print_r($tmp);
//输出
Array
(
    [0] => Array
        (
            [id] => 1
            [pid] => 0
            [name] => 1-1
            [son] => Array
                (
                    [0] => Array
                        (
                            [id] => 2
                            [pid] => 1
                            [name] => 1-1-2
                            [son] => Array
                                (
                                    [0] => Array
                                        (
                                            [id] => 3
                                            [pid] => 2
                                            [name] => 1-1-2-3
                                        )

                                )

                        )

                )

        )

    [1] => Array
        (
            [id] => 4
            [pid] => 0
            [name] => 1-4
            [son] => Array
                (
                    [0] => Array
                        (
                            [id] => 5
                            [pid] => 4
                            [name] => 1-4-5
                        )

                )

        )

    [2] => Array
        (
            [id] => 6
            [pid] => 0
            [name] => 1-6
        )

)

你可能感兴趣的:(php递归)