<?php namespace app\models; use yii\db\ActiveRecord; use Yii; use yii\helpers\ArrayHelper; /* * 商品分类模型类 */ class Category extends ActiveRecord { public static function tableName() { return "{{%category}}"; } public function rules() { return [ ['pid', 'required', 'message' => '父级id不能为空'], ['title', 'required', 'message' => '分类标题不能为空'], ['create_time', 'safe'] ]; } public function attributeLabels() { return [ 'pid' => '父分类', 'title' => '分类标题', 'create_time' => '创建时间' ]; } /* * 分类添加 */ public function add($data) { $r = false; $data['Category']['create_time'] = time(); if ($this->load($data) && $this->validate()) { //通过验证在去处理数据库 $r = $this->save(); // 返回布尔:true false } return $r; } //获取无限级分类的几个联合处理方法 /* * 获取所有分类 */ public function getData() { $cates = self::find()->all(); $cates = ArrayHelper::toArray($cates); //转成数组 return $cates; } /* * 根据父id归类排序 */ public function getTree($cates, $pid = 0) { $tree = []; foreach ($cates as $k => $v) { if ($v['pid'] == $pid) { $tree[] = $v; $tree = array_merge($tree, $this->getTree($cates, $v['cate_id'])); } } return $tree; } /* * 结构化排序好的数据(这个算法的思路) */ public function setPrefix($data, $p = "|-------") { $tree = []; $num = 1; $prefix = [0 => 1]; while ($val = current($data)) { $key = key($data); if ($key > 0) { if ($data[$key - 1]['pid'] != $val['pid']) { $num++; } } if (array_key_exists($val['pid'], $prefix)) { $num = $prefix[$val['pid']]; } $val['title'] = str_repeat($p, $num) . $val['title']; $prefix[$val['pid']] = $num; $tree[] = $val; next($data); //指针移动到下一个元素 } return $tree; } /* * 控制器调用这里返回处理好的列表,里面综合以上几个方法的联合调用 */ public function getTreeList() { $data = $this->getData(); $tree = $this->getTree($data); return $tree = $this->setPrefix($tree); } /* * 用于添加的时候选择分类,带了值和分类名称 */ public function getOptions() { $data = $this->getData(); $tree = $this->getTree($data); $tree = $this->setPrefix($tree); $options = ['0' =>'顶级分类']; foreach ($tree as $k => $v) { $options[$v['cate_id']] = $v['title']; } return $options; } }
商品分类无限级分类处理小例子
最新推荐文章于 2021-04-07 14:52:58 发布