Hiyas,
I've made the following script to build a tree style navigation from a
table of sections for an image gallery. There are root nodes of the tree
which can have children, and those children can have their own children and
so on to an infinte depth. A root node has a parentID of 0 and a child node
has a parentID of the row id you want the child to belong to. (I've faked
the arrays that would be returned from MySQL for this example).
The script is rendering items in the correct order, but I can't keep track
of how deep in the tree each item is so I can indent them properly. A root
node should have a 0 depth, it's child should have 1, and it's child again
should be 2, then the next child of the root should go back to 1. It seems
to be working right until it gets to "rusted" (see eg).
I can figure that I'm adding items to the lastNode array but not removing
them properly nor am I decrementing $x which is what should be keeping
partial track of how deep I am. I figure this is where I'm going wrong but
can't for the life of me figure it out. The calling of huntChild within
itself is killing me.
The script at the moment is:
" . $depth . " - " . $key[1] . "";
$lastNode = array();
array_unshift($lastNode,$key[0]);
huntChildren($children,$key[0]);
}
function huntChildren($childArray,$rootID) {
global $depth;
global $lastNode;
$x = 0;
for ($i = 0; $i < sizeof($childArray); $i++) {
// Suck out the first child node into a new array.
$tmpChild = array_shift($childArray);
// Check to see if the parentID in $tmpChild matches the id of the node
passed ($rootID) when the function is called.
// A match means that the child has the node as a parent.
if ($rootID == $tmpChild[2]) {
if ($lastNode[0] != $tmpChild[2]) {
$x++;
array_unshift($lastNode,$tmpChild[2]);
}
if ($x > 1) {
$depth = sizeof($lastNode) - $x;
} else {
$depth = sizeof($lastNode);
}
echo $depth . " - " . $tmpChild[1] . "";
// Go see if this child has children.
huntChildren($childArray,$tmpChild[0]);
} else {
// If there are no children to the node passed, put $tmpChild array
back into the passed array of children for the next iteration.
array_push($childArray,$tmpChild);
}
}
}
?>
and should generate:
0 - skatey
1 - parks
2 - regular visits
3 - concrete
4 - chipped
3 - metal
4 - rusted
2 - regular stacks
3 - blood spills
3 - guts everywhere
2 - regular zzz
1 - equipment
0 - me
1 - 0-10 years old
1 - 10-20 years old
2 - skeg phase
0 - friends
Aside from the depth problem the script functions just the way I want it
to, but if anyone wants to point out or fix any major problems as well as
my depth one, it'd be much appreciated.
Apologies for any shoddy indenting and the massive post. Trying to give as
much info as I can.
Thanks,
Kris.
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, e-mail: [EMAIL PROTECTED]
To contact the list administrators, e-mail: [EMAIL PROTECTED]