Created
February 25, 2016 10:55
-
-
Save anonymous/4a3c6a3a05f7a699077e to your computer and use it in GitHub Desktop.
tree without recursion
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function buildTree($data, $parentID = 0) { | |
// build a tree using references and not recursion | |
$references = array(); | |
$tree = array(); | |
foreach ($data as $id=> &$node) { | |
// Use id as key to make a references to the tree and initialize it with node reference. | |
$references[$node['id']] = &$node; | |
// Add empty array to hold the children/subcategories | |
$node['children'] = array(); | |
// Get your root node and add this directly to the tree | |
if ($node['parentID']==$parentID) { | |
$tree[$node['id']] = &$node; | |
} else { | |
// Add the non-root node to its parent's references | |
$references[$node['parentID']]['children'][$node['id']] = &$node; | |
} | |
} | |
return $tree; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment