zoukankan      html  css  js  c++  java
  • yii框架无限极分类的做法

    用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 yiidbQuery();
            $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 yiihelpersArrayHelper;
    
    <?= $form->field($model, 'parent_id')->dropDownList(ArrayHelper::map($data,'cat_id','new_cat_name') ,['prompt' => '请选择父级分类']) ?>
  • 相关阅读:
    原型
    构造函数
    异常处理
    逻辑中断
    1. 两数之和
    面向对象(进阶篇)
    面向对象(初级篇)
    面向对象
    迭代器/生成器
    模块&字符格式化
  • 原文地址:https://www.cnblogs.com/georgelu/p/6680989.html
Copyright © 2011-2022 走看看