douqun1977 2011-01-26 17:48
浏览 19

多级别类别列表/树php功能

I'm looking for a php function or mysql stored procedure which outputs the following:

1: category 1 > category 2 > category 3 > category 4
2: category 1 > category 2 > category 3 > category 4
...
n: category n > category o > category p > category p

so basically i want last level category id and text which display all parent categories in hierarchy as above. I have the following table: categories(id,title,level,parentid); level increases with category depth.

I tried much on google but could not find a solution. can you please help me?

thanks -Navi

  • 写回答

1条回答 默认 最新

  • dqd72925 2011-01-26 17:53
    关注

    You can do somethig like this:

    $result = mysql_query("SELECT * FROM categories WHERE level = 1");
    $branches = 0;
    $tree= array();
    while($rows = mysql_fetch_array($result)){
        echo "X->".$rows['title']."<br>";
        $GLOBALS['tree'][$branches][] = $rows['title'];
        getChildren($rows['id'], $branches);
        $branches ++;
    }
    
    function getChildren($id, $index){
        $query = "SELECT * FROM categories WHERE parentid = $id;";
        $result = mysql_query($query);
        while($rows = mysql_fetch_array($result)){
            echo $index."->".$rows['title']."<br>";
            $GLOBALS['tree'][$index][] = $rows['title'];
            getChildren($rows['id'], $index);
        }
    }
    
    echo "<pre>";
    print_r($tree);
    echo "</pre>";
    

    You will have all "branches" in the variable $tree, from then just use foreach to get through the branches...

    Hope this helps

    评论

报告相同问题?