Trees are all around us… inside and outside our computers. As you may have already seen on your daily basis work, when you deal with tree-like structures binded to tables into your DB, you set something like
id | id_father | name | other datas
01 | 00 | root | ...
02 | 01 | sub node | ...
this kind of data structure is usually managed via recursion, and in web applications is useful to store site menu, product categories, file-system alike apps and so on.
The class i’m seeding here does all the dirty job giving you the possibility to
- use custom callback to modify the default behaviour [<ul><li> sequence]
- minimize/maximize function [for folder-like interfaces]
- navigation path serialization
those are the methods usually needed for day-to-day work with trees.
here you find all the code, but I’d like to poin out two things that [IMHO] really teach something to the average PHP programmer
- in the constructor 3 arrays are build as properties starting from the original array: arrayById, arrayByFather, arrayHasChild. I don’t know if it would be faster using array_find.. but once we’ve made the proper index association, ther’s no need for the original array to be parsed again.
- use of $$ for the callback function: not so many people knows this sintax, but it’s worth a try
the rest is really simple, and it’s well commented as well.
of course it fits perfectly with the standard output from dbmanager class presented here. Set up your table in an appropriate way, make your assocQuery call and use your tree in no time.

Leave a Reply