I have a set of objects in a hierachy. There's a top "root" node and that has child nodes, which in turn have child nodes etc. I'm trying to save this structure into a DB using the nested set model, where each "side" of each node is numbered to define the hierarchy, as in Managing Hierarchical Data in MySQL:
(source: mysql.com)
My problem is calculating the left and right values. I typically use RecursiveIteratorIterator to iterate over the hierarchy, but I cant work out how to calculate the numbers without resorting to a recursive function that parses an index variable by reference.
Any ideas?
It's probably of no use, but this is the (incorrect) code I currently have:
$iterator = new RecursiveIteratorIterator(
new Node_List(array($root)),
RecursiveIteratorIterator::SELF_FIRST);
$i = 0;
foreach ($iterator as $node) {
$node->left = ++$i;
$node->right = ++$i;
}
As you can see, that would give something like this:
Node
Node
Node
Left and right values of:
Node (1, 2)
Node (3, 4)
Node (5, 6)
When they should be:
Node (1, 6)
Node (2, 3)
Node (4, 5)