php 遞迴一棵樹

weixin_34162695發表於2018-04-17

基於yii2框架:

controller:

public function actionDigui()

{

    $uid = $this->current_user['uid'];

    $userid = '';

    $dataWxUsers = WxUsers::getWxusersByuid($uid);

    if (!empty($dataWxUsers)) {

        $userid = $dataWxUsers['userid'];

}

    $mydata = self::getWeiXininfo($userid);

    $data = WxUserRelation::getMySub($userid);

    $list = [

        'name' => isset($mydata['nickname']) ? $mydata['nickname'] : '',

        'title' => '下級列表',

        'relationship' => ['children_num'=>count($data)],

        'children'=>$data

    ];

    print_r($list);

    die;

}

WxUserRelation這個model中新增2個方法:

public static function getMySub($userid)

{

    $mysub = self::getSubordinate($userid);

    if (!empty($mysub)) {

        foreach ($mysub as $key => $value) {

            $mysub[$key]['children'] = self::getMySub($value['userid']);

}

        return $mysub;

}

}

/**

* 獲取我的下級

* @param $userid

* @return array|\yii\db\ActiveRecord[]

*/

public static function getSubordinate($userid)

{

    if (empty($userid)) {

        return [];

}

    $data = self::find()->select('userid')->where(['parentuserid' => $userid])->asArray()->all();

    $number = self::find()->select('userid')->where(['parentuserid' => $userid])->count();

    if (!empty($data)) {

        foreach ($data as $key => $value) {

            $weixininfo = self::getWeiXininfo($value['userid']);

            $data[$key]['title'] = !isset($value['userid']) ? '' : $value['userid'];

            $data[$key]['name'] = isset($weixininfo['nickname']) ? $weixininfo['nickname'] : '';

            $data[$key]['relationship'] = [

                'children_num' => $number,

                'parent_num' => 1,

                'sibling_num' => 1

            ];

}

}

    return empty($data) ? [] : $data;

}


6626109-390272dbe371ef2f.png


6626109-f2ee11df3f924650.png


6626109-836e52b4167dca12.png


6626109-ea6a3069d0bb0083.png
最終效果

http://www.htmleaf.com/jQuery/Chart/201602233135.html

相關文章