I have a PHP algorithm (from here) that creates the structure below in the chart from a db table like:
id name parent
1 company 0
2 Sales department 1
3 Sales unit I 2
4 Sales unit II 2
5 Purchase Department 1
6 Controlling 1
7 Controlling unit I 6
Here is the HTML equivalent of the tree structure (ignore CSS at this stage)
<ul class="tree">
<li>Company
<ul>
<li>Purchase Department</li>
<li>Controlling
<ul>
<li> Controlling unit I</li>
</ul>
</li>
<li>Sales Department
<ul>
<li>Sales Unit I</li>
<li>Sales Unit II</li>
</ul>
</li>
</ul>
</li>
</ul>
The PHP algorithm is a recursive algorithm very similar to the below:
function generateTree ($parent) {
global $arrPCat, $arrCat;
if (array_key_exists($parent, $arrPCat)) {
echo '<ul' . ($parent == 0 ? ' class="tree"' : '') . '>';
foreach ($arrPCat[$parent] as $arrC) {
echo '<li>' . $arrC['name'] . '</li>';
generateTree($arrC['id']);
}
echo '</ul>';
}
}
The tree above is quite wide and I am intending to compact it like the graph below (again please ignore CSS):
Here is the HTMl code that I borrowed from here:
<ul class="orgchart">
<li class="root">
<div class="nodecontent">President</div>
<ul>
<li class="node">
<div class="nodecontent">Vice President <br/> Account Services</div>
<ul>
<li class="vertical">
<div class="nodecontent">Account Supervisor</div>
<ul>
<li class="leaf">
<div class="nodecontent">Account Executive</div>
</li>
<li class="leaf">
<div class="nodecontent">Account Executive</div>
</li>
</ul>
</li>
<li class="leaf">
<div class="nodecontent">Account Supervisor</div>
</li>
</ul>
</li>
<li class="vertical">
<div class="nodecontent">Vice President <br/> Creative Services</div>
<ul>
<li class="leaf">
<div class="nodecontent">Art / Copy</div>
</li>
<li class="leaf">
<div class="nodecontent">Production</div>
</li>
</ul>
</li>
<li class="vertical">
<div class="nodecontent">Vice President <br/> Marketing Services</div>
<ul>
<li class="leaf">
<div class="nodecontent">Media</div>
</li>
<li class="leaf">
<div class="nodecontent">Research</div>
</li>
</ul>
</li>
<li class="vertical">
<div class="nodecontent">Vice President <br/> Management Services</div>
<ul>
<li class="leaf">
<div class="nodecontent">Accounting</div>
</li>
<li class="leaf">
<div class="nodecontent">Purchasing</div>
</li>
<li class="leaf">
<div class="nodecontent">Personnel</div>
</li>
</ul>
</li>
</ul>
</li>
</ul>
In this example, the leaf nodes are vertical only. However, the other nodes are cleverly classed by node
, leaf
and vertical
. How can I modify the PHP algorithm above to get the same structure as this compact one efficiently. Node that in my case there could be 1000 nodes so an efficient algorihm is the key. Sorry for the long question!