php - Multi Dimensional Associative Array of Arrays -
so have next code:
$options = array( 'navigation' => array( 'page_title' => 'test', 'menu_title' => 'test_title', 'capabillity' => '', 'menu_slug' => '', 'function' => '', 'icon_url' => '', 'position' => '', 'sub_menues' => array( array( 'page_title' => 'test', 'menu_title' => 'test_title', 'menu_slug' => 'bla' ), array( 'page_title' => 'apples', 'menu_title' => 'test_apples', ), // set of navigations ) ), 'settings' => array( array( 'option_group' => 'bla', 'option_name' => '', 'sanitize_call_back' => '' ) ), 'core_template' => 'path/to/admin/template.phtml' ); foreach($options $setting=>$option){ if($setting == 'navigation' && is_array($option)){ foreach($option $k=>$v){ if(is_array($v)){ foreach($v $sub_menu){ foreach($sub_menu $sk=>$sv){ if(isset($sub_menu[$sk])){ echo $sub_menu['menu_slug']; } } } } if(isset($option[$k])){ echo $option['page_title']; } } } if($setting == 'settings' && is_array($option)){ foreach($option $settings_options){ foreach($settings_options $sk => $sv){ if(isset($settings_options[$sk])){ echo $settings_options['option_group']; } } } } if($setting = 'core_template'){ echo $options['core_template']; } } which, yes mess , needs refactored, works until throw in variable doesn't exist. way see this:
echo $sub_menu['menu_slug']; now menu_slug exists in navigation/sub_menues/[0] array, not in [1]array.
the typical way prepare is:
if(isset($sub_menu['menu_slug'])){ // } how ever can see navigation array, there going a lot of if set this, else that. , looking cleaner , neater way can $sub_menu['something'] , automatically checks see if exists , if so, returns value, if not nothing, ignore it.
now have right idea, *if set $sub_menu[$sk]* , do:
echo $sub_menu[$sk]; the problem calling function in here takes in arguments, arguments values of key, hence why have $sub_menu['menu_slug'] example.
so question is:
how do like:
some_function_call($sub_menu['menu_slug']); with out having do:
if(isset($sub_menu['menu_slug']) && isset($sub_menu['page_title']) /*...and on...*/){ some_function_call($sub_menu['menu_slug'], $sub_menu['page_title'] /*..and on...*/); } the catch? - options, such (say example) menu slug, might optional.
any ideas?
well, if you're keys unique relatively levels, do:
array_walk_recursive($options, function($value, $key){ if($value && in_array($key, array('menu_slug', 'page_title', 'option_group', 'core_template'))) print $value; }); :)
but assume real purpose wrap text in html strings, should utilize switch instead of if statement , print whatever want. if need print stuff in order, utilize temporary array store output generate, , print after you're done.
php arrays function multidimensional-array arguments
No comments:
Post a Comment