PHP在多维数组中创建动态数组 [英] PHP create dynamic array in a multidimensional array

查看:83
本文介绍了PHP在多维数组中创建动态数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想基于多维数组中的数字动态创建一个数组

I want to dynamic create an array based on a number inside a multidimensional array

这里是代码

$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个名称,描述,类型,str相同但名称不同的数组。

I want the last array to be created dynamic by a number so if the number is 2 there must be 2 arrays in there with the same name,desc,type,str but a diffrent ID.

这可能是某种方式吗?

推荐答案

只需通过遍历id的数量来动态添加它们即可:

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);

演示

这篇关于PHP在多维数组中创建动态数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆