I have a set of data:
id | name | parentid
------------------------
1 | parent | 0
2 | child | 1
3 | child | 1
4 | parent | 0
5 | child | 4
6 | subchild | 5
7 | child | 4
Which I can map to a hierarchy that looks like:
1 parent
2 |-- child
3 |-- child
4 parent
5 |-- child
6 |-- subchild
7 |-- child
At the moment, I'm using a recursive function that checks for children, but this is really slow.
function dothings(currentid) {
//do stuff for item
//check if anything has a parentid of currentid
if (let children = checkforchildren(currentid) > 0) {
foreach(children as child) {
dothings(child['id']);
}
}
}
Is there a best practice when working with data that needs to be mapped into an arbitrarily deep array?
(If it matters, I'm using MySQL and PHP to handle this. I can provide more information specific to my use case if that's necessary, but I am looking for a best practice here, not just optimization debugging.)