Skip to content

Instantly share code, notes, and snippets.

@augustyip
Created May 20, 2014 04:07
Show Gist options
  • Save augustyip/f0c6b532ca0b303820a7 to your computer and use it in GitHub Desktop.
Save augustyip/f0c6b532ca0b303820a7 to your computer and use it in GitHub Desktop.
To get a nested tree in Drupal 7
<?php
function taxonomy_get_nested_tree($terms = array(), $parent = 0, $parents_index = array(), $max_depth = NULL, $depth = 0) {
foreach ($terms as $term) {
foreach ($term->parents as $term_parent) {
if ($term_parent == $parent) {
$return[$term->tid] = $term;
}
else {
$parents_index[$term_parent][$term->tid] = $term;
}
}
}
foreach ($return as &$term) {
if (isset($parents_index[$term->tid]) && (is_null($max_depth) || $depth < $max_depth)) {
$term->children = taxonomy_get_nested_tree($parents_index[$term->tid], $term->tid, $parents_index, $max_depth, $depth + 1);
}
}
return $return;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment