Is there a way of storing and working (adding ,removing etc..) with tree data structure in PHP and Mysql?
Can PHP’s RecursiveItrator Itrator be of any use here?
So basically I wanna have tree structures, to store some hierarchies like Categories of some products that can go on indefinitely, It would be very nice to be able to store everything in database, fetch them and do simple things like BFS and DSF traversals in them.
A good way to get all the nodes for a given tree when you use Adjacency List is to add a column to every row called
root_idor something, so every node knows not only its immediate parent, but also the top node in its tree.So if you have a hierarchy of 10 -> 20 -> 30, you’d store the following:
This is similar to how Slashdot stores trees of comments for example.
If you can write a query to fetch all the nodes of a given tree, and each node knows its immediate parent, in the style of the Adjacency List design of storing hierarchical data, you can convert the query result set into a multidimensional array or tree of objects as you fetch it.
See my answer to Convert flat array to the multi-dimentional for code to do this in PHP.