Get all nodes from a menu tree

Photo by Markus Spiske on Unsplash

 

Our Drupal expert helps you out: How to get a list of all nodes in a menu tree in Drupal 7

 

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 the node ids of all the nodes in the main menu:

 

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