我有一个包含以下字段的 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/