0

我正在使用https://github.com/blt04/doctrine2-nestedset来管理我的分层数据。

它使用以下数据库结构管理层次结构:

 categories
 -id
 -root
 -lft
 -rgt
 -name

我需要用 li 标签包装一个节点,如下所示:

 Vehicles
    Bikes
       Pulsor
       Hero Honda
    Automobiles
    Trucks

这个包提供了以下操作节点的方法:

$tree=fetchTreeAsArray($nodeId);  //fetches tree for that node
$node->getNumberDescendants();    //returns all descendants for that node

更多方法描述在https://github.com/cbsi/doctrine2-nestedset/blob/master/README.markdown

我想将节点包裹在 li 标签周围:

到目前为止我试过这个:

         $tree = $nsm->fetchTreeAsArray(8);
    $treeLiTags="<ul>";
    foreach ($tree as $node) {
        $treeLiTags.="<li>".$node;
        if ($node->hasChildren()) {
            echo $node->getNumberDescendants();
            $treeLiTags.="<ul>";
            $closeParent=true;
        }
        else {
            if ($closeParent && !$node->hasNextSibling()) {
                $closeParent=false;
                $treeLiTags.="</ul>";
            }
            $treeLiTags.="</li>";
        }
    }
    $treeLiTags.="</ul>";
    echo $treeLiTags;

这将返回如下:

Vehicles
    Bikes
       Pulsor
       Hero Honda
          250 cc
       Automobiles
       Trucks

我应该得到:

Vehicles
   Bikes
      Pulsor
      Hero Honda
         250 cc
   Automobiles
   Trucks

任何算法都会有帮助吗?

4

1 回答 1

1

您是否考虑过使用嵌套集(树)的Doctrine Extensions 实现?

它已经实现了您想要实现的目标 - 您可以简单地使用:

$repo = $em->getRepository('Entity\Category');
$options = array(
    'decorate' => true,
    'rootOpen' => '<ul>',
    'rootClose' => '</ul>',
    'childOpen' => '<li>',
    'childClose' => '</li>',
    'nodeDecorator' => function($node) {
        return '<a href="/page/'.$node['slug'].'">'.$node[$field].'</a>';
    }
);
$htmlTree = $repo->childrenHierarchy(
    null, /* starting from root nodes */
    false, /* load all children, not only direct */
    $options
);
于 2013-03-13T20:39:27.750 回答