Reputation: 3760
I am using https://github.com/blt04/doctrine2-nestedset to manage my hierarchical data.
It manages hierarchy with following database structure:
categories
-id
-root
-lft
-rgt
-name
I need to wrap a node with li tags as below:
Vehicles
Bikes
Pulsor
Hero Honda
Automobiles
Trucks
This bundle provides with following methods for manipulating a node:
$tree=fetchTreeAsArray($nodeId); //fetches tree for that node
$node->getNumberDescendants(); //returns all descendants for that node
More description of methods at https://github.com/cbsi/doctrine2-nestedset/blob/master/README.markdown
I want to wrap the node around li tags:
I tried so far this:
$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;
This returns as below:
Vehicles
Bikes
Pulsor
Hero Honda
250 cc
Automobiles
Trucks
I should be getting:
Vehicles
Bikes
Pulsor
Hero Honda
250 cc
Automobiles
Trucks
Any algorithm would be helpful?
Upvotes: 0
Views: 273
Reputation: 3260
Have you considered using Doctrine Extensions implementation of nested set (tree)?
It already has implemented what you are trying to achieve - you can simply use:
$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
);
Upvotes: 1