Skip to content

Instantly share code, notes, and snippets.

Created February 25, 2016 10:55

Revisions

  1. @invalid-email-address Anonymous created this gist Feb 25, 2016.
    23 changes: 23 additions & 0 deletions CategoryRepository.php
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    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;
    }