2

我试图弄清楚如何使用 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
4

2 回答 2

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
于 2013-03-18T07:37:19.507 回答
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
于 2013-06-14T01:34:38.297 回答