我想基于多维数组中的数字动态创建数组
这是代码
$meta_box = array(
'id' => 'my-meta-box',
'title' => 'Custom Input Fields',
'page' => 'page',
'context' => 'normal',
'priority' => 'high',
'fields' => array (
array( //this array must be created dynamic
'name' => 'Textarea',
'desc' => 'Enter big text here',
'id' => 'textarea', //id is textarea + number
'type' => 'textarea',
'std' => 'Default value'
)
)
);
我希望最后一个数组是由一个数字动态创建的,所以如果数字是2,那么必须有2个数组,其名称相同,desc,type,str但是不同的ID。
这可能是某种方式吗?
答案 0 :(得分:6)
通过迭代id的数量来动态添加它们:
$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);
答案 1 :(得分:2)
这是一种将每个'fields'子数组作为新数组添加到更大数组
的方法$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>';
您将在浏览器中获得如下输出:
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
)
)
)
答案 2 :(得分:0)
首先按如下方式创建数组$ meta_box:
$meta_box = array(
'id' => 'my-meta-box',
'title' => 'Custom Input Fields',
'page' => 'page',
'context' => 'normal',
'priority' => 'high',
'fields' => array ()
);
然后你可以按如下方式添加'动态'数组:
$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'
);
}
这将启动ID为1的编号,直到$ number。