php - 用于列出同一表中类别的树层次结构的算法

标签 php sql algorithm treeview

我有一个包含以下字段的 SQL 表 tbl_categories:

id , parent , title

例如,该表可能包含以下信息:

id   parent  title
1     0      the main item
2     1      first sub item
3     1      second sub item
4     2      first sub sub item 
5     3      second sub sub item

例如:1 是顶级类别,2 和 3 是 1 的子级,4 是 2 的子级,5 是 3 的子级。

我想使用 PHP 像树结构一样列出这些信息,如下所示:

- 1. the main item
 -- 2.first sub item
  ---4.first sub sub item
 -- 3. second sub item
  ---5.second sub sub item

并考虑根据树中项目的级别添加“-”。

所以问题是:适合此任务的算法是什么?

最佳答案

我假设您使用 MySQL:

<?php
// connect to the database
$dbh = new PDO("mysql:host=127.0.0.1;port=3306;dbname=test", "root", "");

// prepare a statement that we will reuse
$sth = $dbh->prepare("SELECT * FROM tbl_categories WHERE parent = ?");

// this function will recursively print all children of a given row
// $level marks how much indentation to use
function print_children_of_id( $id, $level ) {
    global $sth;
    // execute the prepared statement with the given $id and fetch all rows
    $sth->execute(array($id));
    $rows = $sth->fetchAll();

    foreach($rows as $row)
    {
        // print the leading indentation
        echo str_repeat(" ", $level) . str_repeat("-", $level) . " ";
        // print the title, making sure we escape special characters
        echo htmlspecialchars($row['title']) . "\n";
        // recursively print all the children
        print_children_of_id($row['id'], $level+1);
    }
}

// now print the root node and all its children
echo "<pre>";
print_children_of_id( 0, 1 );
echo "</pre>";
?>

关于php - 用于列出同一表中类别的树层次结构的算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8041867/

相关文章:

mysql - 在mysql中查找同一列的两个连续行之间的差异

mysql - 很少使用mysql表中的字段会降低性能吗?

algorithm - 位排列的通用算法

从一组节点创建链表的算法

php - AJAX 结果不等待查询完成

php - 如何在 while 循环中对项目进行分组?

php - 使用 sleep() 或 cron 作业

sql - 大表的问题(没有可用的主键)

javascript - 将 HTML 参数传递给 php 页面

multithreading - 已经处理许多并发结果中的两个,优化 - 架构?算法?