/** * 获取前辈ID (ID号) *@param $types array 分类结果集 *@param $id int 本类ID *@param $pid int 要获取分类的父ID *@return int 返回类ID */ function getTopId($types, $id, $pid = 0) { $str = ''; foreach ($types as $v) { if ($v['pid'] != $pid) { if ($v['id'] == $id) { $str = $v['pid']; $st = getTopId($types, $v['pid']); if ($st) { $str = $st; } } } } return $str; }
public function getBrands() { $id = I('id'); $types = M('type')->field('id,pid')->select(); $typeId = getTopId($types, $id); //获取顶级分类 if (!$typeId) { $typeId = $id; //如果没有父类,去本类 } $brands = M("brands"); $data = $brands->field('id,type_id,name')->select(); //遍历得到含有类别$typeId的品牌 foreach ($data as $v) { $index = strpos($v['type_id'], "{$typeId}"); //返回查找的类ID在品牌type_id 字串中出现位置 //判断品牌中是否有查找的类,有则组合进数组,(二维) if ($index !== false) { $brandList['id'][] = $v['id']; $brandList['name'][] = $v['name']; } } $this->ajaxReturn($brandList); //ajax返回所需品牌数据 }