I want to build a tree view made of departments(parent) and sub-departments(child). In my database I think I have a good structure which is like this:
--------------------------------------------
Dep_name | dep_id | dep_parent_id
--------------------------------------------
Accounting | 1 | 0
Human-Resources | 2 | 0
IT | 3 | 0
Network | 4 | 3
Web Development | 5 | 3
Front-End | 6 | 5
Back-End | 7 | 5
Departments which have the dep_parent_id 0 ---> they do not have a parent department. For example, Web Development and Network are children of IT department. Front End and Back End are children of Web Development.
I have found a recursive function which is appropriate to get all the data from this database table and put them on an array in te right structure. But the problem is that I dont know how to display this array like a tree view. Like this for example
- Departments
- Accounting
- Human Resources
- IT
- Network
- Web Development
- Front End
- Back End
..... and so on ....
In my database I think I have a good structure which is like this:
I have tried to print the array in a very simple way using
print_r($tree);
And it prints it like this:
Array (
[0] => stdClass Object (
[Dep_name] => Accounting and Finance
[dep_id] => 1
[dep_parent_id] => 0
)
[1] => stdClass Object (
[Dep_name] => Human-Recources
[dep_id] => 2
[dep_parent_id] => 0
)
[2] => stdClass Object (
[Dep_name] => IT
[dep_id] => 3
[dep_parent_id] => 0
[children] => Array (
[0] => stdClass Object (
[Dep_name] => Network
[dep_id] => 5
[dep_parent_id] => 3
)
[1] => stdClass Object (
[Dep_name] => Web Development
[dep_id] => 6
[dep_parent_id] => 3
[children] => Array (
[0] => stdClass Object (
[Dep_name] => Front-End
[dep_id] => 7
[dep_parent_id] => 6
)
[1] => stdClass Object (
[Dep_name] => Back-End
[dep_id] => 8
[dep_parent_id] => 6
)
)
)
)
)
[3] => stdClass Object (
[Dep_name] => Marketing
[dep_id] => 4
[dep_parent_id] => 0
[children] => Array (
[0] => stdClass Object (
[Dep_name] => web-marketing
[dep_id] => 9
[dep_parent_id] => 4
)
)
)
)
This is my function that gets data from database table from array $data and builds a tree array $branch.
function buildTree(array $data, $parentId = 0)
{
$branch = array();
foreach ($data as $element)
{
if ($element->dep_parent_id == $parentId)
{
$children = buildTree($data, $element->dep_id);
if ($children)
{
$element->children = $children;
}
$branch[] = $element;
}
}
return $branch;
}
And than I print it using :
print_r(buildTree($data));
I would be very grateful if you would help me to solve this and display a tree view structure in html from array $branch that I return from function buildTree($data)
.