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 に答える