php 生成菜单数组

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了php 生成菜单数组相关的知识,希望对你有一定的参考价值。

/* Generate custom menu array */
function b_get_menu_id( $location )
{
  $a = get_nav_menu_locations();
  if (isset($a[$location])) return $a[$location];
  return false;
}
function b_get_menu_items( $location )
{
  $navItems = [];
  foreach (wp_get_nav_menu_items( b_get_menu_id($location) ) as $obj) {
    $item = new stdClass();
    $item->url = $obj->url;
    $item->label = $obj->title;
    $item->icon = $obj->classes[0];
    $item->id = $obj->object_id;
    array_push($navItems, $item);
  }
  return $navItems;
}
/* Dropdown menu */
function b_get_nav_items($location) {
  $id = b_get_menu_id($location);
  $nav = [];
  $children = [];
  if(!$id) {
    return $nav;
  }
  foreach(wp_get_nav_menu_items($id) as $object) {
    $item = new stdClass();
    $item->url = $object->url;
    $item->label = $object->title;
    $item->id = $object->object_id;
    $item->icon = $object->classes[0];
    $item->parent = intval($object->menu_item_parent);
    $item->children = [];
    if($item->parent){
      $children[] = $item;
    } else {
      $nav[$object->ID] = $item;
    }
  }
  foreach($children as $item) {
    $nav[$item->parent]->children[] = $item;
  }
  return $nav;
}
<ul class="nav-menu">
	@foreach(b_get_nav_items('primary_navigation') as $item)
		<li class="nav-item {{ $item->icon }}">
			<a href="{{ $item->url }}">{{ $item->label }}</a>

			@if( $item->children )
				<div class="sub-nav">
					<ul class="sub-nav-group">
						@foreach( $item->children as $sub )
						<li>
							<a href="{{ $sub->url }}">{{ $sub->label }}</a>
						</li>
						@endforeach
					</ul>
				</div>
			@endif

		</li>
	@endforeach
</ul>

以上是关于php 生成菜单数组的主要内容,如果未能解决你的问题,请参考以下文章

PHP PHP选项选择菜单生成器功能 - 下拉菜单

PHP选项选择菜单生成器函数-下拉菜单

使用 javascript/jquery 数组生成选择菜单

php 多维数组排序[未显示固定菜单选项]

PHP 获取菜单项数组

微信菜单php 数组格式