如何用PHP显示分层的“NESTED SET”数据?

时间:2013-03-18 07:22:50

标签: php mysql

我正在试图弄清楚如何使用php显示嵌套的MySQL数据。我设法将所有“叶子节点”放在一边,但后来我被困住了。我需要显示整棵树及其所有元素的关系。 这是表格

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分: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