In WordPress I’m trying to create a metabox script from scratch to better understand both WordPress and PHP.
I’m having some problems with a for each loop on a multidimensional array though. I’m using PHP5.
This is the array:
$meta_box = array();
$meta_box[] = array(
'id' => 'monitor-specs',
'title' => 'Monitor Specifications',
'context' => 'normal',
'priority' => 'default',
'pages' => array('monitors', 'products'),
'fields' => array(
array(
'name' => 'Brand',
'desc' => 'Enter the brand of the monitor.',
'id' => $prefix . 'monitor_brand',
'type' => 'text',
'std' => ''
)
)
);
And this is the for each loop:
foreach ($meta_box['pages'] as $post_type => $value) {
add_meta_box($value['id'], $value['title'], 'je_format_metabox', $post_type, $value['context'], $value['priority']);
}
What I’m trying to do is loop through the keys in the ‘pages’ array which is an array inside the ‘meta_box’ array and at the same time be able to use the key values of the ‘meta_box’ array.
Do I need to nest some for each loops?
Would be grateful for some pointers in the right direction so I can solve this.
or
Your
foreach
starts with$meta_box['pages']
, but there is no$meta_box['pages']
.You do have a
$meta_box[0]['pages']
though, so you need two loops:What were you expecting to be in your
$value
variable?this here:
suggests that there is no $meta_box[‘pages’]. meta_box is an array with numerical indexes (check the [] operator) and each of its elements is an array that has the key ‘pages’.
so you need to use foreach on $meta_box, and on each element you need to use the pages key.. id, title, context are elements on the same level as pages, as you can see
You are referencing to the wrong array key
But, you refer using :-
Add the array key will solve the problem :-
Maybe it could be nice to create some class to hold this information.
Now you can loop over the meta_box array like:
Now you still have a loop in a loop, but maybe helps seeing your problem more clearly.