NYCPHP Meetup

NYPHP.org

[nycphp-talk] Flattening a Tree

Ajai Khattri ajai at bitblit.net
Thu Feb 26 00:26:14 EST 2009


On Wed, 25 Feb 2009, csnyder wrote:

> You have to pass your new array by reference, but you also have to
> pass the current key you're working on so that it can be prepended to
> new keys as you traverse them.

Yep, I was using array_merge and that's wrong. Im dealing with a list of 
objects so that made it a little confusing but I got it working. In this 
case I was dealing with a tree of categories where each category has a 
parent_node and the top-level categories have a parent_node of zero. So it 
was something like:

function getsubcategories($parent_id, &$list)
{
	$categories = getcategorieswithparent($parent_id);
	if ($categories != NULL)
	{
		foreach ($categories as $category)
		{
			// append object
			$list[] = $category;
			getsubcategories($category->parent_id(), $list);
		}
	}
}

getsubcategories(0, $current_list);


Im using this to populate a pulldown in a form with a nice function to 
show the pathname to each category.



-- 
Aj.




More information about the talk mailing list