arrays - Modifying a PHP collection -
for wordpress website i'm developing, i'm making dynamic menu users can make using admin menu. hooking least of problems.
the code i'm using returns these arrays:
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] => ) )
to explain: if menu_item_parent = 0, means top-node, , if menu_item_parent > 0, means 'subnode'.
i want convert horrible array more useful, preferably this
array ( [35] => array ( name => "topnode" url => "http://topnodeurl" items => array ( name => "subnode" url => "http://subnodeurl" ) ) )
i thought: hey, couldn't hard. but, apparently, doesn't seem work:
foreach($menuitems $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); } }
any ideas?
make recursive function
function make_menu($items, $parent_id = 0) { $menu = []; foreach($items $key => $item) { if (item['menu_item_parent'] == $parent_id ) { $item['childs'] = make_menu($items, $item['id']); $menu[] = $item; // helps speed foreach removing items not needed more unset($item[$key]); } } return $menu; }
this way can have deeper function 1 layer
Comments
Post a Comment