/**
  * Helper function that transforms a flat taxonomy tree in a nested array.
  */
 public static function getNestedList($tree = array(), $max_depth = NULL, $parent = 0, $parents_index = array(), $depth = 0)
 {
     foreach ($tree as $term) {
         foreach ($term->parents as $term_parent) {
             if ($term_parent == $parent) {
                 $return[$term->id()] = $term;
             } else {
                 $parents_index[$term_parent][$term->id()] = $term;
             }
         }
     }
     foreach ($return as &$term) {
         if (isset($parents_index[$term->id()]) && (is_null($max_depth) || $depth < $max_depth)) {
             $term->children = TaxonomyManagerTree::getNestedList($parents_index[$term->id()], $max_depth, $term->id(), $parents_index, $depth + 1);
         }
     }
     return $return;
 }