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

时间:2011-01-26 17:48:55

标签: php sql tree

我正在寻找输出以下内容的php函数或mysql存储过程:

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

所以基本上我想要最后一级别类别文本,它们显示层次结构中的所有父类别,如上所述。我有下表: 类别(ID,标题,水平,parentId的); 级别随着类别深度而增加。

我在谷歌上做了很多但是找不到解决方案。你能帮我么?

感谢 -Navi

1 个答案:

答案 0 :(得分:0)

您可以这样做:

$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>";

你将在变量$ tree中拥有所有“分支”,然后只需使用foreach来通过分支......

希望这有帮助

相关问题