Skip to content

Instantly share code, notes, and snippets.

Created February 25, 2016 10:55
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save anonymous/4a3c6a3a05f7a699077e to your computer and use it in GitHub Desktop.
Save anonymous/4a3c6a3a05f7a699077e to your computer and use it in GitHub Desktop.
tree without recursion
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