I have a database with a table, in which data is stored as a nested set. The table looks like this:
id lft rgt name depth
0 1 768 ROOT 0
550300 2 3 external 1
580943 4 5 teachers 1
510000 6 753 company BV 1
213000 7 14 Buying 2
913010 8 9 buying center 3
573100 10 11 buying generic 3
516300 12 13 buying service center 3
513900 15 48 finance 2
The data represents a company structure. I would like to display it with jstree
I thought the best way to do that, was to first place it in a multidimensional array. For that I used this function:
function _formatTreeIntoArray(&$tree, $current_depth = 0)
{
$formattedTree = array();
while($leaf = current($tree))
{
if($leaf['depth'] > $current_depth)
{
$formattedTree[] = _formatTreeIntoArray($tree, $leaf['depth']);
}
elseif($leaf['depth'] < $current_depth)
{
return $formattedTree;
}
else
{
$formattedTree[] = $leaf;
next($tree);
}
}
return $formattedTree;
}
that I found here: https://gist.github.com/taion809/6510212 and slightly modified.
It seems to be doing a pretty good job (Tried the solution in here before, but there I was losing nodes: How do I format Nested Set Model data into an array?)
Now my next challenge it to create a jtree out of it, which should either look like this:
<div id="html1">
<ul>
<li>Root node 1
<ul>
<li>Child node 1</li>
<li><a href="#">Child node 2</a></li>
</ul>
</li>
</ul>
</div>
or this:
$('#using_json').jstree({ 'core' : {
'data' : [
'Simple root node',
{
'text' : 'Root node 2',
'state' : {
'opened' : true,
'selected' : true
},
'children' : [
{ 'text' : 'Child 1' },
'Child 2'
]
}
]
} });
I found a function in this topic: PHP Array to jsTree , but since the function that turns the nested set into a array creates many array entries without a name for the key, I get a lot of extra levels in the tree with just a number as name, and without the proper children.
I was wondering how I could solve this, and if there's maybe a better way to achieve my goal.