yii框架无限极分类的实现方法
用yii框架做了一个无限极分类,主要的数组转换都是粘贴的别人的代码,但还是不要脸的写出来,方便以后自己看
用的是递归,不是path路径
控制器:
protectedfunctionsubtree($arr,$id=0,$lev=1){
$subs=array();//子孙数组
foreach($arras$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;
}
publicfunctionactionCreate()
{
$model=newEcsCategory();
$query=new\yii\db\Query();
$query->select('*')
->from('ecs_category');
$command=$query->createCommand();
$res=$command->queryAll();
$tree=$this->subtree($res,0,1);
foreach($treeas$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'=>'请选择父级分类'])?>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。
热门推荐
10 朋友新年祝福语大全 简短
11 新年祝福语简短大方兔年
12 搬新家礼物祝福语简短
13 同学见面花束祝福语简短
14 五一假期祝福语幽默简短
15 离职欢送敬酒祝福语简短
16 对学弟的祝福语简短
17 考老师辞职祝福语简短
18 祝福语驱散霉运的话简短