我使用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
有什么算法会有帮助吗?
您考虑过使用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
);