我怎样才能将它变成递归函数。这样它就会得到所选parent_id的所有类别的列表?
public function getProductCategoryPath($product_id) {
$query = $this->db->query("SELECT category_id FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "' LIMIT 1");
if($query->row['category_id']){
// Parent category
$path = $query->row['category_id'];
// Category parent
$query = $this->db->query("SELECT parent_id FROM " . DB_PREFIX . "category WHERE category_id = '" . $query->row['category_id'] . "' AND parent_id != 0");
if($query->num_rows){
$path = $query->row['parent_id'] . "_" . $path;
// Sub-category parent
$query = $this->db->query("SELECT parent_id FROM " . DB_PREFIX . "category WHERE category_id = '" . $query->row['parent_id'] . "' AND parent_id != 0");
if($query->num_rows){
$path = $query->row['parent_id'] . "_" . $path;
}
}
return $path;
}
return false;
}
答案 0 :(得分:3)
我并不完全明白你想要打印什么,但是对于递归你将使用
public function getProductCategoryPath($product_id) {
$query = $this->db->query("SELECT category_id FROM " . DB_PREFIX . "product_to_category WHERE product_id = '" . (int)$product_id . "' LIMIT 1");
if($query->row['category_id']){
// Parent category
$path = $query->row['category_id'];
// Category parent
$query = $this->db->query("SELECT parent_id FROM " . DB_PREFIX . "category WHERE category_id = '" . $query->row['category_id'] . "' AND parent_id != 0");
while($query->num_rows){
$path = $query->row['parent_id'] . "_" . $path;
// Sub-category parent
$query = $this->db->query("SELECT parent_id FROM " . DB_PREFIX . "category WHERE category_id = '" . $query->row['parent_id'] . "' AND parent_id != 0");
}
return $path;
}
return false;
}