Yii2.0 无限级分类列表

方法一: 递归实现

递归原理:

递归: 调用程序自身的方法.

如:

function deep (&$i)
{
    echo $i;
    $i++;
    if($i < 10){
    	deep($i);
    }
}
// 递归查上级
public static function Pname ($username)
{
    $line = array();
    $line = self::tree($username);
    return $line;
}

public static function tree($username, $line = [])
{
    $data = UserModel::find()->select(['id','username','parent_name'])->where(['username'=>$username])->asArray()->all();
    if (!empty($data)){
        foreach ($data as $v)
        {
            $id = $v['id'];
            $username = $v['username'];
            $pname = $v['parent_name'];
            if (!empty($pname)) {//
                $line[] = html::a(
                    $pname."  =>&nbsp;&nbsp;&nbsp; ",
                    ['user/pname','username'=>$pname],
                    ['style'=>'color:gray;']
                );
                $line = self::tree($pname, $line);
            }else{
                $line[] = '没有上级了';
            }
        }
    }
    return $line;
    // echo "<pre>";
    // print_r($line);
}

eg 无限级分类:

//获取数据
public static function getData ()
{

    return $data = Attributelist::find()->orderBy('order desc')->asArray()->all();
    // echo "<pre>";
    // print_r($data);
}
//生成树
public function getTree ($data, $pid=0, $nu=0)
{
    $bx = "|——";
    $nu++ ;
    if (!empty($data)) {
        foreach ($data as $v)
        {
            $dataid = $v['id'];
            $datapid = $v['pid'];
            $dataname = $v['name'];
            if ($datapid == $pid) {//
                $this->tree[$dataid] =  str_repeat($bx, $nu).$dataname;
                $this->getTree($data,$v['id'],$nu);
            }
        }
    }
}
public function tree()
{
    $data = $this->getData();
    $this->getTree($data, 0, 0);
    return $this->tree;
}



导航