php - 修改关联数组中深层键的值

标签 php arrays

假设我们有一个简单的 $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/

相关文章:

php - 如何解决 Joomla 错误 "The template for this display is not available."

另一个数组内的 Javascript 数组(多维)

java - Java中二维数组中每个维度的长度

javascript - 从 php 多维数组填充 javascript 数组

php - REGEXP 在 PHP 脚本中未按预期工作

java - 无法从 android php 连接插入 MySql Db

php - 如何更新 php5.6-curl 以便它可以验证新的 LetsEncrypt X1 证书?

php - 如何通过phpword库读取表格单元格内容

arrays - 将引用和未引用内容混合的文件读取到 bash 数组中,保留引号

ruby - 计算 Ruby 数组中的 Fixnums