0

我怎么能把它变成一个递归函数。这样它会获得所选 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;
}
4

1 回答 1

3

我不完全了解您要打印的内容,但是对于递归,您将使用 while

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;
}
于 2012-12-23T22:20:06.983 回答