Build a tree from a flat array in PHP

You forgot the unset() in there bro. function buildTree(array &$elements, $parentId = 0) { $branch = array(); foreach ($elements as $element) { if ($element[‘parent_id’] == $parentId) { $children = buildTree($elements, $element[‘id’]); if ($children) { $element[‘children’] = $children; } $branch[$element[‘id’]] = $element; unset($elements[$element[‘id’]]); } } return $branch; }

create array tree from array list

oke this is how i solved it: $arr = array( array(‘id’=>100, ‘parentid’=>0, ‘name’=>’a’), array(‘id’=>101, ‘parentid’=>100, ‘name’=>’a’), array(‘id’=>102, ‘parentid’=>101, ‘name’=>’a’), array(‘id’=>103, ‘parentid’=>101, ‘name’=>’a’), ); $new = array(); foreach ($arr as $a){ $new[$a[‘parentid’]][] = $a; } $tree = createTree($new, array($arr[0])); print_r($tree); function createTree(&$list, $parent){ $tree = array(); foreach ($parent as $k=>$l){ if(isset($list[$l[‘id’]])){ $l[‘children’] = createTree($list, $list[$l[‘id’]]); } … Read more

How to flatten tree via LINQ?

You can flatten a tree like this: IEnumerable<MyNode> Flatten(IEnumerable<MyNode> e) => e.SelectMany(c => Flatten(c.Elements)).Concat(new[] { e }); You can then filter by group using Where(…). To earn some “points for style”, convert Flatten to an extension function in a static class. public static IEnumerable<MyNode> Flatten(this IEnumerable<MyNode> e) => e.SelectMany(c => c.Elements.Flatten()).Concat(e); To earn more points … Read more

What are the options for storing hierarchical data in a relational database?

My favorite answer is as what the first sentence in this thread suggested. Use an Adjacency List to maintain the hierarchy and use Nested Sets to query the hierarchy. The problem up until now has been that the coversion method from an Adjacecy List to Nested Sets has been frightfully slow because most people use … Read more