我正在使用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
任何算法都会有帮助吗?
答案 0 :(得分:1)
您是否考虑过使用Doctrine Extensions的nested set (tree)实施?
它已经实现了你想要实现的目标 - 你可以简单地使用:
$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
);