Jump to content

Get children from hierarchical database


tibberous

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/223462-get-children-from-hierarchical-database/
Share on other sites

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);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.