views:

84

answers:

1

I am reading the following article, http://articles.sitepoint.com/article/hierarchical-data-database/2 about"Storing Hierarchical Data in a Database".

This is talking about these structures. http://sitepointstatic.com/graphics/sitepoint_numbering.gif and http://sitepointstatic.com/graphics/table02.gif

I don't understand the following passages. What do these mean.

"Each time you start with the children of a node, you add the right value of that node to the stack."

and

"When you're finished displaying a node, you remove its right value from the stack. If you count the elements in the stack, you'll get the level of the current node."

I am hoping someone explains these in a simpler way if possible.

To show the tree structure, children should be indented slightly more than their parent. We can do this by keeping a stack of right values. Each time you start with the children of a node, you add the right value of that node to the stack. You know that all children of that node have a right value that is less than the right value of the parent, so by comparing the right value of the current node with the last right node in the stack, you can see if you're still displaying the children of that parent. When you're finished displaying a node, you remove its right value from the stack. If you count the elements in the stack, you'll get the level of the current node.

+1  A: 

They're trying to come up with a way to use Nested Sets for indenting data by the level in the tree.

Food (1,12)
|
+--Fruit (2,11)
  |
  +--Red (3,6)
  | |
  | +--Cherry (4,5)
  |
  +--Yellow (7,10)
    |
    +--Banana (8,9)

So as you fetch the rows, you push the rgt number onto the end of an array:

$right[] = $row['rgt'];

This array grows as you process children and subchildren. For example, by the time we get to "Cherry" the array looks like this:

array(11, 6, 5)

As long as we're descending down a branch of the tree, the rgt values in this should be getting less, because a child's rgt value is always less than its parent's rgt value.

The next row we process is "Yellow" which has a rgt value of 10. This value 10 is greater than the last value in the array, which means we're not descending down one branch anymore, we're on a different branch. We need to pop numbers out of the array until 10 is no longer greater than the last number in the array.

array(11, 6) // 10 is still greater than 6
array(11)    // 10 is not greater than 11, so stop

Now we know that the array contains only ancestors of our current row "Yellow".

The level in the tree is always equal to the number of elements in that array.

Bill Karwin