2013-03-18 69 views
2

我想弄清楚如何使用php顯示嵌套的MySQL數據。我設法把所有的「葉節點」放在一邊,但後來我被困住了。我需要顯示一棵整棵樹以及它所有元素的關係。 這裏的表如何使用PHP顯示分層的「嵌套SET」數據?

category_id, name, lft, rgt 
1 Saws 1 12 
2 Chainsaws 2 7 
3 Red 3 4 
4 Yellow 5 6 
5 Circular saws 8 9 
6 Other saws 10 11 

下面是代碼:

$query = 'SELECT node.name, node.lft, node.rgt 
    FROM item_cats AS node, 
     item_cats AS parent 
    WHERE node.lft BETWEEN parent.lft AND parent.rgt AND parent.name = "' . SAWS . '" 
    ORDER BY node.lft'; 
$result = mysql_query($query, $db) or die (mysql_error($db)); 
while ($row = mysql_fetch_assoc($result)) { 
    if ($row['rgt'] == $row['lft']+1) { 
     echo '==>'; 
    } 
    echo $row['lft']; 
    echo $row['name']; 
    echo $row['rgt']; 
    echo '<br />'; 
    echo '<br />'; 
} 

而這就是我得到:

1Saws12 
2Chainsaws7 
==>3Red4 
==>5Yellow6 
==>8Circular saws9 
==>10Other saws11 
+0

什麼是RGT和LFT? – 2013-03-18 07:26:15

+2

@AdamPlocher [嵌套集模型](http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/),向下滾動到'嵌套集模型'標題,第一位是關於不同的技術 – Stu 2013-03-18 07:27:55

+0

啊有趣。謝謝 – 2013-03-18 07:29:46

回答

3

基於鏈接的Stu給我看,本教程顯示了這個查詢確定深度:

SELECT node.name, (COUNT(parent.name) - 1) AS depth 
FROM nested_category AS node, 
     nested_category AS parent 
WHERE node.lft BETWEEN parent.lft AND parent.rgt 
GROUP BY node.name 
ORDER BY node.lft 

所以這樣的事情應該工作:

<?PHP 
$query = 'SELECT node.name, (COUNT(parent.name) - 1) AS depth 
    FROM nested_category AS node, 
      nested_category AS parent 
    WHERE node.lft BETWEEN parent.lft AND parent.rgt 
    GROUP BY node.name 
    ORDER BY node.lft'; 

$result = mysql_query($query, $db) or die (mysql_error($db)); 
while ($row = mysql_fetch_assoc($result)) { 
    for ($i = 0; $i < $row['depth']; $i++) { 
     echo '==>'; 
    } 

    echo $row['name']; 
    echo '<br />'; 
    echo '<br />'; 
} 
?> 

這應該輸出:

Saws 
==>Chainsaws 
==>==>Red 
==>==>Yellow 
==>Circular Saws 
==>Other Saws 
+0

謝謝,我會嘗試 – 2013-03-18 07:47:01

+0

啊拍,對不起,我剛剛發現一個錯誤......那裏'parent.name =「saws」'導致深度返回0 ...讓我試着修復它。 – 2013-03-18 07:48:13

+0

是的,我注意到了!謝謝,這個作品! – 2013-03-18 07:49:46

1
<?PHP 
$query = ' 
    select if(
     count(a.name) - 1 = 0, 
     a.name, 
     concat(repeat(' ', count(a.name) - 2), '+--', b.name) 
    )name 
    from nested_category b, nested_category a 
    where node.lft between a.lft and a.rgt 
    group by b.name 
    order by b.lft'; 

$result = mysql_query($query, $db) or die (mysql_error($db)); 
while ($row = mysql_fetch_assoc($result)) echo "{$row['name']}<br>"; 
?> 

應該做某事,如:

Saws 
+--Chainsaws 
    +--Red 
    +--Yellow 
+--Circular Saws 
+--Other Saws 
相關問題