I would like to convert a list of values such as:
$foo = ['a', 'b', 'c'];
将其转换为遍历数组键的列表,例如:
$bar['a']['b']['c'] = 123;
我如何创建一个关联数组,其键基于存储在另一个数组中的一组值?
I would like to convert a list of values such as:
$foo = ['a', 'b', 'c'];
$bar['a']['b']['c'] = 123;
<?php
$foo = ['a', 'b', 'c'];
$array = [];
$current = &$array;
foreach($foo as $key) {
@$current = &$current[$key];
}
$current = 123;
print_r($array);
$foo = ['a', 'b', 'c'];
$val = '123';
foreach (array_reverse($foo) as $k => $v) {
$bar = [$v => $k ? $bar : $val];
}
这里还有另一种选择:创建一个临时可解析的字符串(通过提取第一个值,然后将其余值作为方括号包装的字符串附加),调用parse_str()
,并将输出变量设置为$bar
。
代码:(演示)
$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',
),
),
)
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
['a', 'b', 'c', 'd']
; 那么输出会变成$bar['a']['b']['c']['d']
吗?它仍然是123吗?还是1234? - Andreas