2011-11-07 61 views
1

我有一個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的子項,4是2的子項,5是3的子項。

我想列出這種信息,就像使用PHP的樹結構一樣, s:

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

並考慮根據樹中項目的等級添加「 - 」。

所以問題是:什麼是適合這項任務的算法?

回答

3

我假設你使用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>"; 
?> 
+0

非常感謝你的朋友...我很抱歉不提及數據庫引擎..是的,我使用的MySQL當然是:-) + 1 – SmootQ