I would like to convert a list of values such as:
$foo = ['a', 'b', 'c'];
into a list of traversing array keys such as:
$bar['a']['b']['c'] = 123;
How I can create an associative array which keys are based on a set values stored in another array?
答案 0 :(得分:4)
You can make it with reference. Try this code, live demo
<?php
$foo = ['a', 'b', 'c'];
$array = [];
$current = &$array;
foreach($foo as $key) {
@$current = &$current[$key];
}
$current = 123;
print_r($array);
答案 1 :(得分:1)
我会这样做:
$foo = ['a', 'b', 'c'];
$val = '123';
foreach (array_reverse($foo) as $k => $v) {
$bar = [$v => $k ? $bar : $val];
}
我们反过来迭代数组并首先分配最里面的值,然后从里到外构建数组。
答案 2 :(得分:0)
这是另一个选项:创建一个临时可解析字符串(通过提取第一个值,然后将其余值附加为方括号包裹的字符串),调用parse_str()
,并将输出变量设置为$bar
代码:(Demo)
$foo = ['a', 'b', 'c'];
$val=123;
parse_str(array_shift($foo).'['.implode('][',$foo)."]=$val",$bar);
// built string: `a[b][c]=123`
var_export($bar);
输出:
array (
'a' =>
array (
'b' =>
array (
'c' => '123',
),
),
)
如果第一种方法感觉过于苛刻,以下递归方法是一种稳定的方法:
代码:(Demo)
function nest_assoc($keys,$value){
return [array_shift($keys) => (empty($keys) ? $value : nest_assoc($keys,$value))];
// ^^^^^^^^^^^^^^^^^^--------------------------------------------------------extract leading key value, modify $keys
// check if any keys left-----^^^^^^^^^^^^
// no more keys, use the value---------------^^^^^^
// recurse to write the subarray contents-------------^^^^^^^^^^^^^^^^^^^^^^^^^
}
$foo=['a','b','c'];
$val=123;
var_export(nest_assoc($foo,$val));
// same output