Get nested taxonomy tree from taxonomy_get_tree

Public

Maps flat taxonomy terms array obtained with taxonomy_get_tree and returns a nested array

</> CopyGet raw version
php
  1. // all credits go to skn3 https://www.drupal.org/node/324730 for this function
  2. function &filter_taxonomy_treedata(&$nvocs) {
  3. //this function will take a flat vocabulary tree and turn it into a multi-tiered array
  4. //the return array will simply contain an array of pointers rather then physical objects
  5. $map = array();
  6.  
  7.  
  8. //go through the tree and find the lowest depth aswell as all available depth levels to scan
  9. $startdepth = false;
  10. $depthlist = array();
  11. foreach($nvocs as $vocindex => &$vocitem) {
  12. if ($startdepth === false || $startdepth > $vocitem->depth) {
  13. //new start depth found
  14. $startdepth = $vocitem->depth;
  15. }
  16.  
  17.  
  18. //add this item to the speciffic depth level
  19. $depthlist[$vocitem->depth][$vocitem->tid] = &$vocitem;
  20. }
  21.  
  22.  
  23. //sort the depthlist so lowest is first
  24. ksort($depthlist);
  25.  
  26.  
  27. //scan all depth levels found
  28. $lastdepth = null;
  29. foreach($depthlist as $depthlevel => &$depths) {
  30. //check for first depth (root) level
  31. $currentdepthdata = array();
  32.  
  33.  
  34. if ($depthlevel == $startdepth) {
  35. //add root items to the map
  36. foreach($depths as $itemindex => &$item) {
  37. $mapindex = count($map);
  38. $map[$mapindex] = array("data" => &$item,"children" => array());
  39. $currentdepthdata[$itemindex] = &$map[$mapindex];
  40. }
  41. } else {
  42. //scan through all items within this depth
  43. foreach($depths as $itemindex => &$item) {
  44. //find a matching "map" in teh last depth to assign the item too
  45. foreach($item->parents as $parentindex) {
  46. $mapindex = count($lastdepthdata[$parentindex]["children"]);
  47. $lastdepthdata[$parentindex]["children"][$mapindex] = array("data" => &$item,"children" => array());
  48. $currentdepthdata[$itemindex] = &$lastdepthdata[$parentindex]["children"][$mapindex];
  49. }
  50. }
  51. }
  52.  
  53.  
  54. $lastdepthdata = $currentdepthdata;
  55. }
  56.  
  57.  
  58. return $map;
  59. }