根据一个分类id 获取这个分类底下所有子分类的商品信息,根据下面方法查询出所有有关分类id 再 根据这些id去商品表里查询所有商品信息
/** * 检测该分类下所有子分类,并输出ID(包括自己) * 数据库字段 catid pid */ function getChildrenIds ($sort_id){ include_once APPPATH.'/libraries/db.php'; $db = new Db(); $ids = $sort_id; $sql = "SELECT catid,pid FROM jy_category WHERE pid =".$sort_id; $result = $db->select($sql); if ($result){ foreach ($result as $key=>$val){ $ids .= ','.$val['catid'].","; $ids .= getChildrenIds ($val['catid']); } } $idsArr = explode(",",$ids); $idsArr = array_unique($idsArr); $ids = implode(",",$idsArr); return $ids; }
/** * 检测该分类下所有子分类,并输出ID(不包括自己) * 数据库字段 catid pid */ function getChildrenIds ($sort_id) { $db = $this->loadDB(); $ids = ''; $sql = "SELECT * FROM t_dept WHERE `parent_id` = '{$sort_id}'"; $query = $db->query($sql); $result = $query->result_array(); if ($result) { foreach ($result as $key=>$val) { $ids .= ','.$val['id']; $ids .= $this->getChildrenIds ($val['id']); } } return $ids; }
上面的查询数据库次数太多了 然后下面这个就好一点,三级分类最多查询三次
/** * 检测该分类下所有子分类,并输出ID */ public function getChildrenIds ($pid,$sort_id){ $aPid = array(); if(!is_array($pid)){ $aPid[]=$pid; }else{ $aPid = $pid; } $sql = "SELECT catid,pid FROM jy_category WHERE pid in({$sort_id})"; $result =$this->db->select($sql); $aSort = array(); $aUnion = array(); if ($result){ foreach ($result as $key=>$val){ $aSort[] = $val['catid']; } $aUnion = $this->getChildrenIds($aSort,implode(",",$aSort)); } return array_merge($aPid,$aUnion); }