PHP |用于为具有键数组的任何多维数组赋值的函数

时间:2017-10-24 09:04:45

标签: php arrays multidimensional-array

我的目标是编写一个函数,为任何多维数组赋值:

<tr>

示例:function array_multidim_set($arr, $keys, $value)应创建一个值,如下所示print_r(array_multidim_set($arr, ['key1', 'key2', 'key'3'], 'foo');

现在我正在使用它:

$arr[key1][key2][key3] = 'foo'

但它仅限于定义的案例数量。有没有办法为任意数量的密钥创建通用函数?

谢谢!

1 个答案:

答案 0 :(得分:3)

尝试以下解决方案:

function array_multidim_set(&$arr, $keys, $value){
    $rv = &$arr;
    foreach($keys as $pk)
    {
        $rv = &$rv[$pk]; // Unused reference [ex. $rv['key1'] then $rv['key1']['key2'] .. so on ] - actually assigned to $target by reference
    }
    $rv = $value;
}

$target = ['test' => 'test'];

array_multidim_set($target, ['key1', 'key2', 'key3'], 'foo');
echo '<pre>';
print_r($target);

<强>输出:

Array
(
    [test] => ttt
    [key1] => Array
        (
            [key2] => Array
                (
                    [key3] => foo
                )

        )

)