I want to dynamic create an array based on a number inside a multidimensional array
here is the code
$meta_box = array(
\'id\' => \'my-meta-box\',
Here's a way to add each 'fields' sub array as a new array into the larger array
$meta_box = array(
'id' => 'my-meta-box',
'title' => 'Custom Input Fields',
'page' => 'page',
'context' => 'normal',
'priority' => 'high');
$fields = array();
$numberOfArrays = 2;
for($i = 1; $i <= $numberOfArrays; $i++){
$fields[$i] = array (
array( //this array must be created dynamic
'name' => 'Textarea',
'desc' => 'Enter big text here',
'id' => 'textarea' . $i, //id is textarea + number
'type' => 'textarea',
'std' => 'Default value'
)
);
}
$meta_box['fields'] = $fields;
echo '<pre>';
print_r($meta_box);
echo '</pre>';
You'll get an output like this in your browser:
Array
(
[id] => my-meta-box
[title] => Custom Input Fields
[page] => page
[context] => normal
[priority] => high
[fields] => Array
(
[1] => Array
(
[name] => Textarea
[desc] => Enter big text here
[id] => textarea1
[type] => textarea
[std] => Default value
)
[2] => Array
(
[name] => Textarea
[desc] => Enter big text here
[id] => textarea2
[type] => textarea
[std] => Default value
)
)
)
Demo
First you create the array $meta_box as follows:
$meta_box = array(
'id' => 'my-meta-box',
'title' => 'Custom Input Fields',
'page' => 'page',
'context' => 'normal',
'priority' => 'high',
'fields' => array ()
);
Then you can add the 'dynamic' arrays as follows:
$number = 2;
for ($i = 1; $i <= $number; $i++) {
$meta_box['fields'][] = array(
'name' => 'Textarea',
'desc' => 'Enter big text here',
'id' => 'textarea_' . $i, //id is textarea + number
'type' => 'textarea',
'std' => 'Default value'
);
}
This starts the numbering for the ids at 1 until $number.
Just add them dynamically by iterating over the number of ids:
$meta_box = array
(
'id' => 'my-meta-box',
'title' => 'Custom Input Fields',
'page' => 'page',
'context' => 'normal',
'priority' => 'high',
'fields' => array ()
);
$dynamicNumber = 2;
$idPrefix = 'textarea';
assert('$dynamicNumber > 0');
$dynamicIds = range(1, $dynamicNumber);
$fields = &$meta_box['fields'];
foreach($dynamicIds as $id)
{
$fields[] = array( //this array must be created dynamic
'name' => 'Textarea',
'desc' => 'Enter big text here',
'id' => sprintf('%s%d', $idPrefix, $id), //id is textarea + number
'type' => 'textarea',
'std' => 'Default value'
);
}
unset($fields);
Demo