当前位置: 移动技术网 > IT编程>开发语言>PHP > yii框架无限极分类的实现方法

yii框架无限极分类的实现方法

2017年12月12日  | 移动技术网IT编程  | 我要评论

笑傲江湖360礼包,cz3920,高加索犬咬死藏獒

用yii框架做了一个无限极分类,主要的数组转换都是粘贴的别人的代码,但还是不要脸的写出来,方便以后自己看

用的是递归,不是path路径

控制器:

protected function subtree($arr,$id=0,$lev=1){
    $subs = array(); // 子孙数组
    foreach($arr as $v) {
      if($v['parent_id'] == $id) {
        $v['lev'] = $lev;
        $subs[] = $v; // 举例说找到array('id'=>1,'name'=>'安徽','parent'=>0),
        $subs = array_merge($subs,$this->subtree($arr,$v['cat_id'],$lev+1));
      }
    }
    return $subs;
  }

public function actioncreate()
  {
    $model = new ecscategory();
    $query = new \yii\db\query();
    $query->select('*')
      ->from('ecs_category');
    $command = $query->createcommand();
    $res=$command->queryall();
    $tree = $this->subtree($res,0,1);
    foreach($tree as $k=> $v) {
      $tree[$k]['new_cat_name']=str_repeat('--',$v['lev']).$v['cat_name'].str_repeat('--',$v['lev']); //str_repeat — 重复一个字符串
    }
    $arr=array(
      'new_cat_name'=>'顶级分类',
      'cat_id'=>0
    );
    array_unshift($tree,$arr);
    if ($model->load(yii::$app->request->post()) && $model->save()) {
      return $this->redirect(['view', 'id' => $model->cat_id]);
    } else {
      return $this->render('create', [
        'model' => $model,
        'data'=>$tree,
      ]);
    }
  }

视图:

 use \yii\helpers\arrayhelper;

<?= $form->field($model, 'parent_id')->dropdownlist(arrayhelper::map($data,'cat_id','new_cat_name') ,['prompt' => '请选择父级分类']) ?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网