美文网首页
php 数组处理成无限极分类的方法

php 数组处理成无限极分类的方法

作者: 全栈coder | 来源:发表于2019-05-23 10:54 被阅读0次
     public  function getSubTree($data , $id = 0 , $lev = 0) {
    
            $son = array();
            $stack = array();
            $stack_tmp = array(); //存下层节点的id们
            $tree= array();
    
            $stack[] = $id;
    
            while(!empty($data)){
    
                foreach ($stack as $k1 => $v1){
    
                    foreach ($data as $key =>$value){
                        if($value['pid'] == $v1){
                            $value['level'] = $lev;
                            $son[] = $value;
                            unset($data[$key]);
                            array_push($stack_tmp , $value['id']);
                            $tree[$lev][] = $value;
                        }
                    }
    
                }
    
                $stack = array();
                $stack = $stack_tmp;
                $stack_tmp = array();
    
                $lev+=1;
    
            }
    
            $num = count($tree)-1;
    
            for($i=$num;$i>0;$i--){
                $j = $i -1;
                foreach ($tree[$j] as $k1=>&$v1){
                    foreach ($tree[$i] as $k2=>&$v2){
                        if($v2['pid'] == $v1['id']){
                            $v1['child'][] = $v2;
                            unset($tree[$i][$k2]);
                        }
                    }
                }
                unset($tree[$i]);
            }
            return $tree;
        }
    

    相关文章

      网友评论

          本文标题:php 数组处理成无限极分类的方法

          本文链接:https://www.haomeiwen.com/subject/owmhzqtx.html