PHP-自动创建多维数组 [英] PHP - Automatically creating a multi-dimensional array
问题描述
所以这是输入:
$in['a--b--c--d'] = 'value';
和所需的输出:
$out['a']['b']['c']['d'] = 'value';
有什么想法吗?我已经尝试了下面的代码,但没有任何运气...
Any ideas? I've tried the following code without any luck...
$in['a--b--c--d'] = 'value';
// $str = "a']['b']['c']['d";
$str = implode("']['", explode('--', key($in)));
${"out['$str']"} = 'value';
推荐答案
这似乎是递归的主要候选对象.
This seems like a prime candidate for recursion.
基本方法如下:
- 创建键数组
- 为每个键创建一个数组
- 没有更多键时,返回值(而不是数组)
下面的递归精确地做到了这一点,在每次调用期间创建一个新数组,将列表中的第一个键指定为新值的键.在下一步中,如果还有键,则重复该过程,但是当没有键时,我们只返回该值.
The recursion below does precisely this, during each call a new array is created, the first key in the list is assigned as the key for a new value. During the next step, if there are keys left, the procedure repeats, but when no keys are left, we simply return the value.
$keys = explode('--', key($in));
function arr_to_keys($keys, $val){
if(count($keys) == 0){
return $val;
}
return array($keys[0] => arr_to_keys(array_slice($keys,1), $val));
}
$out = arr_to_keys($keys, $in[key($in)]);
对于您的示例,上面的代码将被评估为与此等效(但在任何数量的--
分隔项目的一般情况下都适用):
For your example the code above would evaluate as something equivalent to this (but will work for the general case of any number of --
separated items):
$out = array($keys[0] => array($keys[1] => array($keys[2] => array($keys[3] => 'value'))));
或更确切地说,它构造以下内容:
Or in more definitive terms it constructs the following:
$out = array('a' => array('b' => array('c' => array('d' => 'value'))));
这允许您通过所需的索引访问每个子数组.
Which allows you to access each sub-array through the indexes you wanted.
这篇关于PHP-自动创建多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!