user410932 user410932 - 4 months ago 36
PHP Question

php tree bottom up

I have a tree structure in my database, eg for employees.

create table "employees" (employee_id, name, manager_id);

where, of course, manager_id is the employee_id (same table) with the manager of that employee.

This can easily be converted to an array, representing the tree structure of the company
(although there is not 1 CEO at the top, the root-node has multiple elements). All fine so far.

Now, to handle registrations, i have an array of employee_ids

$registrations = array(3,7, 10);

I'd need to show those in the tree structure, where only the managers of those employees are shown (but up to the top of the tree). Does anybody have an algorithm for this? I managed to add them to the tree, but didn't manage to putg the different branches together when 2 people share 1 manager.

Say employee 3 and 10 (cfr above) share the same manager with ID 15, and employee 7 has manager with ID 23, where both managers report to the same manager with ID 33, who in his turn reports to 45: I'd need an array

array('45'=>array('33'=>array('23'=>array(7), '15'=>array(3,10))));

I do manage to build this structure, eg starting with employee 3, I get


and while looping for employee 7, I manage to build the branch


but how can i now merge this new array in the already existing one ... ? I know that the manager of 23 is 33, but how do I a) find that it needs to be added to the tree, and b) add it to the tree ath the correct place??? anybody?


My opinion is that you have chosen the wrong way to store tree data into your database.

If you like to store tree data into your database you have to use Modified Preorder Tree Traversal.

More information about this way of storing trees in database you can find here :

With this algorithm you can manage your data in any order you like and you can easily extract whatever information you like!