So I have the following 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 as $setting=>$option){
if($setting == 'navigation' && is_array($option)){
foreach($option as $k=>$v){
if(is_array($v)){
foreach($v as $sub_menu){
foreach($sub_menu as $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 as $settings_options){
foreach($settings_options as $sk => $sv){
if(isset($settings_options[$sk])){
echo $settings_options['option_group'];
}
}
}
}
if($setting = 'core_template'){
echo $options['core_template'];
}
}
Which, yes is a mess and needs to be refactored, works UNTIL you throw in a variable that doesn’t exist. a good way to see this:
echo $sub_menu['menu_slug'];
now menu_slug exists in navigation/sub_menues/[0] array, but not in [1]array.
The typical way to fix this is:
if(isset($sub_menu['menu_slug'])){ // do something }
How ever as you can see from the navigation array, there is going to be A LOT of if is set do this, else do that. and I am looking for a cleaner and neater way where I can just do $sub_menu[‘something’] and it automatically checks to see if something exists and if so, returns its value, if NOT do nothing, just ignore it.
Now I have the right idea, where I do *if is set $sub_menu[$sk]* and then I could do:
echo $sub_menu[$sk];
the problem is I am calling a function in here that takes in arguments, the arguments are the values of the key, hence why I have to do $sub_menu[‘menu_slug’] for example.
So my question is:
How do I do something like:
some_function_call($sub_menu['menu_slug']);
with out having to do:
if(isset($sub_menu['menu_slug']) && isset($sub_menu['page_title']) /*...and so on...*/){
some_function_call($sub_menu['menu_slug'], $sub_menu['page_title'] /*..and so on...*/);
}
The catch? – some options, such as (say for example) menu slug, might be optional.
Any ideas?
Well, if you’re keys are unique relatively to all levels, you could do:
🙂
But I assume that your real purpose is to wrap this text in HTML strings, so you should use
switchinstead of myifstatement and print whatever you want. If you need to print the stuff in a certain order, use a temporary array to store the output you generate, and print it after you’re done.