假设我们有一个简单的 $array
像下面这样。
$array = array(
'a' => array(
'b' => array(
'c' => 'd'
),
'e' => 'f'
),
'g' => 'h'
);
给定一个任意数组 $keys = array('a', 'b', 'c')
和一个值$value = 'i'
,我想更改 $array['a']['b']['c']
的值至i
.
为简单起见,我们假设 $keys
的元素都是有效的,即对于任何正 j
, $keys[j]
存在并且是 $keys[j - 1]
的子项.
我通过传递对数组的引用并循环键来想出了一个解决方案,但我的实现看起来有点难看。有没有直接的方法可以做到这一点?
最佳答案
// 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
关于php - 修改关联数组中深层键的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41971730/