Recursive function to get all children in a menu

Public

A function to get all menu children (regardless of depth) of a given mlid and menu

</> CopyGet raw version
php
  1. /**
  2.  * A function to get all menu children (regardless of depth) of a given mlid
  3.  * @param type $mlid
  4.  * @param type $menu
  5.  * @return $children a multidimensional array of nodes in menu structure
  6.  */
  7. function get_all_menu_children($mlid, $menu = 'main-menu') {
  8. $tree = menu_tree_all_data($menu);
  9. $children = array();
  10. if ($mlid) {
  11. foreach ($tree as $branch) {
  12.  
  13. $check = _find_mlid_in_menu($mlid, $branch);
  14.  
  15. if ($check) {
  16. $branch = $check;
  17. foreach ($branch['below'] as $twig) {
  18. $alias = url_parts($twig['link']['link_path']);
  19. if ($alias[0] == 'node') {
  20. $n = node_load($alias[1]);
  21. $children['node/' . $n->nid]['title'] = $twig['link']['link_title'];
  22. }
  23. if ($twig['below']) {
  24. $children['node/' . $n->nid]['children'] = get_all_menu_children($twig['link']["mlid"]);
  25. foreach ($twig['below'] as $t) {
  26. $alias = url_parts($t['link']['link_path']);
  27. }
  28. }
  29. }
  30. }
  31. }
  32. }
  33. return $children;
  34. }
  35.  
  36.  
  37. /**
  38.  * Helper function for get_all)menu_children() that recursively search an menu, this should not be called directly.
  39.  *
  40.  * @param int $mlid - The menu link id
  41.  * @param array $link - The menu tree item
  42.  * @return array | null
  43.  */
  44. function _find_mlid_in_menu($mlid, $link) {
  45. if ($mlid == $link['link']['mlid']) {
  46. return $link;
  47. }
  48. else {
  49. foreach ($link['below'] as $k => $item) {
  50. $response = _find_mlid_in_menu($mlid, $item);
  51. if ($response) {
  52. return $response;
  53. }
  54. }
  55. }
  56. }
  57.  
  58. /**
  59.  * Returns an array containing the parts of the request uri with slashes trimmed and query removed.
  60.  *
  61.  * @param string $uri - The uri to work from, defaults to current (NULL)
  62.  * @return array
  63.  */
  64. function url_parts($uri = NULL) {
  65. if (!$uri) {
  66. $uri = explode('?', request_uri());
  67. return explode('/', trim($uri[0], '/'));
  68. }
  69. else {
  70. return explode('/', trim($uri, '/'));
  71. }
  72.  
  73. return NULL;
  74. }