How to: Get all the nodes from a menu tree

Posted on: Thu, 12/08/2016 - 17:56 By: Darko
Drupal, get nodes list from a menu tree

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());

Sharethis