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

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.