Get all nodes from a menu tree

  • Posted on: 12 August 2016
  • By: Darko

I wanted to get list of all nodes in a menu tree in Drupal 7, so I wrote this recursive  function

function array_flatten($array, $return) {
  foreach($array as $arr) {
    if($arr['below']) {
      $return = array_flatten($arr['below'], $return);
    }
    else {
      $nid = explode('/', $arr['link']['link_path']);
      if($nid[0] == 'node') {
        $return[] = $nid[1];
      }
    }
  }
  return $return;
}

 

So to get the array consisting of  node ids of  all nodes in a main menu

$myarray = menu_build_tree('main-menu');
$res = array_flatten($myarray, array());