I have a table called "page" with the fields, ID, parentID, and name. It's a relational database setup so parentID would be the ID of another row in the page table - this of course allows for sub-categories of unlimited depth. What I need to do is to find the path back to the root page (highest level) and put each step (a page name) into an array called $path. So, let's say I have this data in my table... Format is: ID|parentID|name 1|0|Fruit 2|1|Apple 3|1|Banana 4|1|Orange 5|2|Red apple 6|2|Green apple The deepest levels are the red apple and green apple pages. So, how could I iterate through so that my $path array would contain the following when starting from the "red apple" category. [0] => "Fruit" [1] => "Apple" [2] => "Red apple" Implementation should be along the lines of.... $path = getThePath($pageID); Thanks!
Not sure if this is the best way, but let me know if it works: <?php function getThePath( $ID ) { $pathArray = array(); $nextID = $ID; while( !is_null( $nextID )) { $resultPage = mysql_query( "SELECT name, parentID FROM page WHERE ID='$nextID'" ); if( $row = mysql_fetch_array( $resultPage )) { $nextID = $row['parentID']; $pathArray[$nextID] = $row['name']; } else { $nextID = NULL; } } return $pathArray; } ?> PHP:
I was just thinking about it, you want the array keys to be numbered according their category level, like root = $array[0], not according to the parentID. Here's the updated code to do this: <?php function getThePath( $ID ) { $pathArray = array(); $nextID = $ID; $i = 0; while( !is_null( $nextID )) { $resultPage = mysql_query( "SELECT name, parentID FROM page WHERE ID='$nextID'" ); if( $row = mysql_fetch_array( $resultPage )) { $nextID = $row['parentID']; $pathArray[$i] = $row['name']; $i++; } else { $nextID = NULL; } } return array_reverse( array_reverse( $pathArray ), true ); } ?> PHP:
Thanks! Was a huge help! It kicked me into the right direction as I applied this to an OO approach. Thanks!