【问题标题】:multi level category listings / tree php function多级类别列表/树 php 函数
【发布时间】:2011-01-26 17:48:54
【问题描述】:

我正在寻找输出以下内容的 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

所以基本上我想要 last level category id在层次结构中显示所有父类别的文本 如上所述。我有下表: 类别(id、title、level、parentid); 级别随类别深度而增加。

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

谢谢 -导航

【问题讨论】:

    标签: php sql tree


    【解决方案1】:

    你可以这样做:

    $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 来通过分支...

    希望对你有帮助

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-28
      • 1970-01-01
      • 2022-11-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多