如何显示和正确缩进树结构

时间:2012-10-02 14:09:59

标签: php tree

DB结构是这样的:

INSERT INTO categories (title, lft, rgt) VALUES ('Cat 1',1,16);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 2',2,3);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 3',4,7);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 4',5,6);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 5',8,13);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 6',9,12);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 7',10,11);
INSERT INTO categories (title, lft, rgt) VALUES ('Cat 8',14,15);  

当我运行此查询时:

SELECT n.title, COUNT(*)-1 AS depth FROM categories AS n, categories AS p WHERE  n.lft BETWEEN p.lft AND p.rgt GROUP BY n.lft ORDER BY n.lft;

$result = mysql_query($query);

// Build array
$tree = array();
while ($row = mysql_fetch_assoc($result)) {
  $tree[] = $row;
}

之后我可以使用以下功能:

// bootstrap loop
    $result = '';
    $currDepth = -1;  // -1 to get the outer <ul>
    while (!empty($tree)) {
      $currNode = array_shift($tree);
      // Level down?
      if ($currNode['depth'] > $currDepth) {
        // Yes, open <ul>
        $result .= '<ul>';
      }
      // Level up?
      if ($currNode['depth'] < $currDepth) {
        // Yes, close n open <ul>
        $result .= str_repeat('</ul>', $currDepth - $currNode['depth']);
      }
      // Always add node
      $result .= '<li>' . $currNode['title'] . '</li>';
      // Adjust current depth
      $currDepth = $currNode['depth'];
      // Are we finished?
      if (empty($tree)) {
        // Yes, close n open <ul>
        $result .= str_repeat('</ul>', $currDepth + 1);
      }
    }

    print $result;

任何人都可以告诉我如何打印树没有 <ul> and <li>.。 我想使用&nbsp;为儿童和子儿童打印它...因为我必须将它放在<select>列表和其他HTML标签中

我在这里可以看到我正在使用的结构:Getting a modified preorder tree traversal model (nested set) into a <ul>

1 个答案:

答案 0 :(得分:0)

作为紧急响应(并且未经测试),因为您已经拥有每个元素/节点的depth,您可以使用它来为每个元素/节点输出多少&nbsp;块,然后结束每行<br />(除非您需要通过其他方式分隔元素)。

尝试输出空格的函数,它应该是这样简单:

function _tab($depth) {
    $tabs = '';
    while ($depth-- > 0) $tabs .= '&nbsp;&nbsp;&nbsp;&nbsp;';
    return $tabs;
}

// bootstrap loop
$result = '';
while (!empty($tree)) {
    $currNode = array_shift($tree);
    $result .= _tab($currNode['depth']) . $currNode['title'] . '<br />';
}

print $result;
相关问题