对于我正在开发的wordpress网站,我正在制作一个用户可以使用管理菜单制作的动态菜单。陷入困境只是我遇到的问题。
我正在使用的代码返回这些数组:
Array
(
[0] => WP_Post Object
(
[ID] => 35
[post_author] => 1
[post_date] => 2013-05-19 15:46:22
[post_date_gmt] => 2013-05-19 15:46:22
[post_content] =>
[post_title] =>
[post_excerpt] =>
[post_status] => publish
[comment_status] => open
[ping_status] => open
[post_password] =>
[post_name] => 35
[to_ping] =>
[pinged] =>
[post_modified] => 2013-05-19 16:07:09
[post_modified_gmt] => 2013-05-19 16:07:09
[post_content_filtered] =>
[post_parent] => 0
[guid] => http://adapt.local/?p=35
[menu_order] => 1
[post_type] => nav_menu_item
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
[db_id] => 35
[menu_item_parent] => 0
[object_id] => 32
[object] => training
[type] => post_type
[type_label] => Training
[url] => http://adapt.local/training/alcohol/
[title] => Alcohol
[target] =>
[attr_title] =>
[description] =>
[classes] => Array
(
[0] =>
)
[xfn] =>
)
[1] => WP_Post Object
(
[ID] => 36
[post_author] => 1
[post_date] => 2013-05-19 16:07:09
[post_date_gmt] => 2013-05-19 16:07:09
[post_content] =>
[post_title] =>
[post_excerpt] =>
[post_status] => publish
[comment_status] => open
[ping_status] => open
[post_password] =>
[post_name] => 36
[to_ping] =>
[pinged] =>
[post_modified] => 2013-05-19 16:07:09
[post_modified_gmt] => 2013-05-19 16:07:09
[post_content_filtered] =>
[post_parent] => 0
[guid] => http://adapt.local/?p=36
[menu_order] => 2
[post_type] => nav_menu_item
[post_mime_type] =>
[comment_count] => 0
[filter] => raw
[db_id] => 36
[menu_item_parent] => 35
[object_id] => 32
[object] => training
[type] => post_type
[type_label] => Training
[url] => http://adapt.local/training/alcohol/
[title] => Alcohol
[target] =>
[attr_title] =>
[description] =>
[classes] => Array
(
[0] =>
)
[xfn] =>
)
)
解释:如果menu_item_parent = 0,则表示它是顶级节点,如果menu_item_parent> 0,表示它是一个'子节点'。
我想把这个可怕的数组转换成更有用的东西,最好是这样的
Array
(
[35] => Array
(
name => "Topnode"
url => "http://topnodeurl"
items => Array
(
name => "Subnode"
url => "http://subnodeurl"
)
)
)
我想:嘿,这可不是那么难。但是,显然,这似乎不起作用:
foreach($menuitems as $menuitem) {
if(!$menuitem->menu_item_parent) {
$items[$menuitem->ID] = array("name" => $menuitem->title,"items" => array());
#print_r($items);
}
else {
$parent = $items[$menuitem->menu_item_parent]['items'];
$parent = array("name" => $menuitem->title, "url" => $menuitem->url);
}
}
有什么想法吗?
答案 0 :(得分:2)
制作递归函数
function make_menu($items, $parent_id = 0)
{
$menu = [];
foreach($items as $key => $item) {
if (item['menu_item_parent'] == $parent_id ) {
$item['childs'] = make_menu($items, $item['ID']);
$menu[] = $item;
// Helps speed up the foreach by removing items that are not needed any more
unset($item[$key]);
}
}
return $menu;
}
这样你就可以拥有更深层的功能,只需要1层