我们假设我们有一个简单的$array
,如下所示。
$array = array(
'a' => array(
'b' => array(
'c' => 'd'
),
'e' => 'f'
),
'g' => 'h'
);
鉴于<{> 1}}的任意数组和值$keys = array('a', 'b', 'c')
,我想将$value = 'i'
的值更改为$array['a']['b']['c']
。
为简单起见,我们假设i
的元素都是有效的,即对于任何正$keys
,j
存在并且是$keys[j]
的孩子
我提出了一个解决方案,通过传递对数组的引用并循环键,但我的实现看起来有点难看。有没有直接的方法呢?
答案 0 :(得分:2)
// current key index (starting at 0)
$i = 0;
// current array (starting with the outermost)
$t = &$array;
// continue until keys are exhausted
while ($i < count($keys) - 1) {
// update array pointer based on current key
$t = &$t[$keys[$i++]];
}
// update value at last key
$t[$keys[$i]] = $value;
http://sandbox.onlinephpfunctions.com/code/0598f00ab719c005a0560c18f91ab00154ba9453