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

2025-05-27 0 60

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

用的是递归,不是path路径

控制器:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38
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,

]);

}

}

视图:

?

1

2

3
use \\yii\\helpers\\ArrayHelper;

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

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

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 yii框架无限极分类的实现方法 https://www.kuaiidc.com/72546.html

相关文章

发表评论
暂无评论