Hey all. I know this has been gone over multiple times here, and I'm finally understanding it (I think.) I'm basing all my work off the Sitepoint article on this, and just modifying their sample code 'til I can get it to do what I want, then I'll clean it up. But right now, I have a demo categories table I'm playing with, and this is the function that displays it:
function displayTree($parentID, $level) {
$result = mysql_query('SELECT `catID`,`catName`,`catParent` FROM categories WHERE catParent="'.$parentID.'";');
// display each child
while ($row = mysql_fetch_array($result)) {
// indent and display the title of this child
echo str_repeat(' -- ',$level).'<a href="categories.php?id='.$row['catID'].'">'.$row['catName']."</a><br />";
// call this function again to display this
// child's children
displayTree($row['catID'], $level+1);
}
}
I call it with
displayTree('',0);
and it outputs this:
Blog Posts
-- July Blogs
-- -- 7/22/07 - 7/28/07
-- August Blogs
-- -- First Week of August
Pages
-- HorizonSM Pages
-- -- News and Updates
-- Tutorials
That all works fine, as does calling just a single subcategory. What I'm playing with now is their code to display the path to a node. The function I've modified slightly is here:
function treePath($catID) {
// look up the parent of this node
$result = mysql_query('SELECT catParent FROM categories WHERE catID="'.$catID.'";');
$row = mysql_fetch_array($result);
// save the path in this array
$path = array();
// only continue if this $node isn't the root node
// (that's the node with no parent)
if ($row['catParent']!='') {
// the last part of the path to $node, is the name
// of the parent of $node
$path[] = $row['catParent'];
// we should add the path to the parent of this node
// to the path
$path = array_merge(treePath($row['catParent']), $path);
}
// return the path
return $path;
}
I call that with
print_r(treePath('8'));
and it outputs:
Array
(
[0] => 0
[1] => 2
[2] => 7
)
That's fine too, I understand what it's doing there. What I'd like to know is, can anyone suggest a way I can tie the category name into the path output? I'm thinking I'll need to use a multidimensional array and I'm just looking for some input on what the best way to do this would be. I'm hoping it'll come out to be something I can cycle through with a for loop, and print out the id number and title of the parent category in the path.
Any help?