I am trying to turn flat mysql rows into a tree structure.
$categories = array(
            array(
                'id' => '1',
                'name' => 'root',
                'parent' => '0',
            ),  
            array(
                'id' => '2',
                'name' => 'first',
                'parent' => '1',
            ),  
            array(
                'id' => '3',
                'name' => 'first',
                'parent' => '1',
            ),  
            array(
                'id' => '4',
                'name' => 'second',
                'parent' => '3',
            ),  
        );  
I am initializing all the first level nodes first then calling build_tree on each node.
    $hierarchy = array();
    // loop through and get each root node
    foreach($categories as $key => $category) {
        if ($category['parent'] == 0) {
            // initialize this root
            $hierarchy[$category['id']] = $category;
            $hierarchy[$category['id']]['children'] = array();
            // remove this from categories
            unset($categories[$key]);
            $this->build_tree($hierarchy[$category['id']], $categories);
        }   
    }   
    return $hierarchy;
}   
function build_tree(&$node, &$categories) {
    foreach ($categories as $key => $category) {
        // check if this node is the parent
        if ($node['id']  === $category['parent']) {
            $node['children'][$category['id']] = $category;
            $node['children'][$category['id']]['children'] = array();
            unset($categories[$key]);
            $this->build_tree($category, $categories);
        }   
    }   
}   
THis is only returning the first and second levels of the tree.
array
  1 => 
    array
      'id' => string '1' (length=1)
      'name' => string 'root' (length=4)
      'parent' => string '0' (length=1)
      'children' => 
        array
          2 => 
            array
              'id' => string '2' (length=1)
              'name' => string 'first' (length=5)
              'parent' => string '1' (length=1)
              'children' => 
                array
                  empty
          3 => 
            array
              'id' => string '3' (length=1)
              'name' => string 'first' (length=5)
              'parent' => string '1' (length=1)
              'children' => 
                array
                  empty
Inside of build_tree when it reaches id=2 it is creating children successfully. (finding that there is one child of id=2 and appending it to 'children' correctly)
It is just not saving it!  Can anyone see what I am doing wrong?? When I var_dump hierarchy it is just the first and second level never the third even though the third is being created successfully in build_tree. Any help would be very greatly appreciated. Ty.
 
    