I have a hierarchy of nodes stored in DB. I select all, store them in an array, then iterate over them and create a nested array in memory.
The input looks like this:
[{name: A}, {name: B}, {name: X, parent: A}, {name: Y, parent: A}, {name: C}]
The output looks like this:
[{name: A, children:[{name: X}, {name: Y}]}, {B}, {C}]
There is no limit on how deep the nesting can go.
The problem I have is that if one of the records has an invalid parent reference, it cannot be put in the hierarchy and the script ends in an infinite loop, trying to find the parent.
I bet there's a way to tell when I've fallen into the infinite loop. For the record, when in the loop I realize there's no parent to insert the item into, I push the item at the end of the array because the parent might exists down the line.
I suppose I should be able to realize that I'm cycling the same items over and over again?
Edit 1 - the code This is the important bit:
$cnt = count($array);
do {
$item = array_shift($array);
if ($this->push($item)) {
$cnt--;
} else {
array_push($array, $item);
}
} while ($cnt > 0);
($this->push() is a method that tries to find a parent and, if it succeeds, inserts $item into its hierarchy)