代码之家  ›  专栏  ›  技术社区  ›  Udders

创建嵌套列表

  •  0
  • Udders  · 技术社区  · 14 年前

    如何创建一个嵌套列表,我目前有这个

    public function getNav($cat,$subcat){
        //gets all sub categories for a specific category
        if(!$this->checkValue($cat)) return false;  //checks data
    
        $query = false;
        if($cat=='NULL'){
            $sql = "SELECT itemID, title, parent, url, description, image 
                    FROM p_cat 
                    WHERE deleted = 0
                    AND parent is NULL
                    ORDER BY position;";
            $query = $this->db->query($sql) or die($this->db->error);
        }else{
            //die($cat);
            $sql = "SET @parent = (SELECT c.itemID FROM p_cat c WHERE url = '".$this->sql($cat)."' AND deleted = 0);
    
                    SELECT c1.itemID, c1.title, c1.parent, c1.url, c1.description, c1.image, (SELECT c2.url FROM p_cat c2 WHERE c2.itemID = c1.parent LIMIT 1) as parentUrl
                    FROM p_cat c1
                    WHERE c1.deleted = 0
                    AND c1.parent = @parent
                    ORDER BY c1.position;";
            $query = $this->db->multi_query($sql) or die($this->db->error);
            $this->db->store_result(); $this->db->next_result();
            $query = $this->db->store_result();
        }
        return $query;
    }
    
    
    public function getNav($cat=false, $subcat=false){
            //gets a list of all categories form this level, if $cat is false it returns top level nav
    
        if($cat==false || strtolower($cat)=='all-products') $cat='NULL';
        $ds = $this->data->getNav($cat, $subcat);
        $nav = $ds ? $ds : false;
        $html = '';
    
        //create html
        if($nav){
            $html = '<ul>';
            //var_dump($nav->fetch_assoc());
            while($row = $nav->fetch_assoc()){
                $url = isset($row['parentUrl']) ? $row['parentUrl'].'/'.$row['url'] : $row['url'];
                $current = $subcat==$row['url'] ? ' class="current"' : '';
                $html .= '<li'.$current.'><a href="/'.$url.'/">'.$row['title'].'</a></li>';
            }
            $html .='</ul>';
        }
        return $html;
    }
    

    SQL返回父级和子级,对于每个父级,我需要子级嵌套在一个列表中。

    1 回复  |  直到 14 年前
        1
  •  0
  •   Greg Stevens    14 年前

    我已经有一段时间没有做过任何PHP了,但我想知道这是否可行。在while循环中,您是否可以在新的<li>中重复并添加getnav($cat=$row['url'])的输出,类似于:

    while($row = $nav->fetch_assoc()){
        $url = isset($row['parentUrl']) ? $row['parentUrl'].'/'.$row['url'] : $row['url'];
        $current = $subcat==$row['url'] ? ' class="current"' : '';
        $html .= '<li'.$current.'><a href="/'.$url.'/">'.$row['title'].'</a>';
        /* Add subNav HTML */
        $html .= $this->getNav($row['url']);
        $html .= '</li>';
    }
    

    看起来“get nav”既指获取SQL的函数,也指呈现nav html的函数——为了清晰起见,可以将html getnav函数名改为getnavhtml。 似乎$subcat参数可以从SQL getnav函数中删除,因为它从未被使用过。