[英]PHP - Automatically creating a multi-dimensional array
So here's the input: 所以这是输入:
$in['a--b--c--d'] = 'value';
And the desired output: 和期望的输出:
$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 basic approach goes something like: 基本方法如下:
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. 这允许您通过所需的索引访问每个子数组。
$temp = &$out = array();
$keys = explode('--', 'a--b--c--d');
foreach ($keys as $key) {
$temp[$key] = array();
$temp = &$temp[$key];
}
$temp = 'value';
echo $out['a']['b']['c']['d']; // this will print 'value'
In the code above I create an array for each key and use $temp to reference the last created array. 在上面的代码中,我为每个键创建一个数组,并使用$ temp来引用最后创建的数组。 When I run out of keys, I replace the last array with the actual value. 当我用完钥匙时,我用实际值替换最后一个数组。 Note that $temp is a REFERENCE to the last created, most nested array. 请注意,$ temp是对最后创建的,嵌套最多的数组的引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.