Skip to content

Instantly share code, notes, and snippets.

@nowendwell
Created January 23, 2017 19:35
Show Gist options
  • Save nowendwell/ed05e7cf7b83c10eab5406746bc6c40d to your computer and use it in GitHub Desktop.
Save nowendwell/ed05e7cf7b83c10eab5406746bc6c40d to your computer and use it in GitHub Desktop.
<?php
/**
* Modification of "Build a tree from a flat array in PHP"
*
* Authors: @DSkinner, @ImmortalFirefly and @SteveEdson
*
* @link http://stackoverflow.com/a/28429487/2078474
*/
function buildTree( array &$elements, $parentId = 0 )
{
$branch = array();
foreach ( $elements as &$element )
{
if ( $element->menu_item_parent == $parentId )
{
$children = buildTree( $elements, $element->ID );
if ( $children ){
$element->has_children = 1;
$element->children = $children;
} else {
$element->has_children = 0;
}
$branch[$element->ID] = $element;
unset( $element );
}
}
return $branch;
}
/**
* Transform a navigational menu to it's tree structure
*
* @uses buildTree()
* @uses wp_get_nav_menu_items()
*
* @param String $menud_id
* @return Array|null $tree
*/
function wpse_nav_menu_2_tree( $menu_id )
{
$items = wp_get_nav_menu_items( $menu_id );
return $items ? buildTree( $items, 0 ) : null;
}
/**
* Call to func
*/
$menu = wpse_nav_menu_2_tree( $menu_id );
print_r($menu);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment