tibberous Posted January 5, 2011 Share Posted January 5, 2011 id Name Owner 1 Root 0 2 Child 1 3 Child 1 4 Level-2-Child 2 So, I want to get an element, then get all elements that are either direct or indirect children of it. So - getChildren(2) should return 2 and 4, because 4 is a direct child of 2. And getChildren(1) should return 1, 2, 3, 4 because all items are a child of root. I'm pretty sure it needs to be done with a recursive function. Can someone help me out? Quote Link to comment https://forums.phpfreaks.com/topic/223462-get-children-from-hierarchical-database/ Share on other sites More sharing options...
johnny86 Posted January 5, 2011 Share Posted January 5, 2011 There are functions made already for that. For example here: http://articles.sitepoint.com/article/hierarchical-data-database Modify them if you need to. Quote Link to comment https://forums.phpfreaks.com/topic/223462-get-children-from-hierarchical-database/#findComment-1155151 Share on other sites More sharing options...
tibberous Posted January 5, 2011 Author Share Posted January 5, 2011 Awesome man! EXACTLY what I needed! Quote Link to comment https://forums.phpfreaks.com/topic/223462-get-children-from-hierarchical-database/#findComment-1155250 Share on other sites More sharing options...
tibberous Posted January 5, 2011 Author Share Posted January 5, 2011 Here is the same function, only setup to return an array of ids, rather than print. Little bit more useful, imo. function get_children($parent, $level) { // retrieve all children of $parent $children = array(); $result = mysql_query('SELECT `id` FROM `pages` WHERE `Owner`="'.$parent.'";'); while ($row = mysql_fetch_array($result)) { $children[] = $row['id']; $children = array_merge($children, get_children($row['id'], $level+1)); } return $children; } get_children($id, 0); Quote Link to comment https://forums.phpfreaks.com/topic/223462-get-children-from-hierarchical-database/#findComment-1155255 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.