yii无限级分类的简单实现

in with 0 comment
    public function sort($data , $pid = 0 )
        {
            $tree = [];
            foreach ($data as $key => $val) {
                if( $val['parentid'] === $pid ) {
                    $tree[] = $val;
                    $tree = array_merge($tree , $this->sort($data , $val['id']));
                }
            }
            return $this->setPrefix($tree);
        }

        public function setPrefix($data ,$p = "|--")
        {
            $tree = [];
            $num = 0;
            $prefix = [0 => 0];

            while( $val = current($data) ){
                $key = key($data); // 7   //8
                if( $key > 0 ) {  // true //true
                    if( $data[$key-1]['parentid'] != $val['parentid'] ) { // true //true // 用来判断 上一个是不是和自己是兄弟关系
                        $num ++ ;  // 0+1  // 1+1 = 2
                    }
                }
                if( array_key_exists( $val['parentid'], $prefix ) ) { // false  // false // 用来判断是不是根id
                    $num = $prefix[$val['parentid']];
                }
                $val['title'] = str_repeat($p,$num) . $val['title'];  // |-- * 1

                $prefix[$val['parentid']] = $num ; // $prefix = [20 => 1];
                $tree[] = $val;
                next($data);
            }

            return $tree;
        }

--- 我感觉我递归都没学会,得找时间多训练,写了又忘记,诶

Comments are closed.