PHP:使用变量作为键设置嵌套数组的值 [英] PHP: Set value of nested array using variable as key

查看:23
本文介绍了PHP:使用变量作为键设置嵌套数组的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这种代码:

    $array = [
        'a'=> [
            'b' => [
                'c'=>'some value',
            ],
        ],
    ];

    $array['a']['b']['c'] = 'new value';

当然这是有效的,但我想要的是使用变量更新这个c"键,就像这样:

Of course this is working, but what i want is to update this 'c' key using variable, something like that:

$keys = '[a][b][c]';
$array{$keys} = 'new value';

但键被视为字符串,这就是我得到的:

But keys are treatening as string and this is what i get:

$array['[a][b][c]'] = 'new value';

所以我需要一些帮助,向我展示在不使用 eval() 的情况下完成这项工作的正确方法.

So i would like some help, to show me the right way to make this work without using eval().

顺便说一下,可以有任意数量的数组嵌套,所以这样的事情不是一个好的答案:

By the way, there can be any number of array nests, so something like this is not a good answer:

$key1 = 'a';
$key2 = 'b';
$key3 = 'c';
$array[$key1][$key2][$key3] = 'new value';

推荐答案

这不是定义键的最佳方式,但是:

It isn't the best way to define your keys, but:

$array = [];
$keys = '[a][b][c]';
$value = 'HELLO WORLD';

$keys = explode('][', trim($keys, '[]'));
$reference = &$array;
foreach ($keys as $key) {
    if (!array_key_exists($key, $reference)) {
        $reference[$key] = [];
    }
    $reference = &$reference[$key];
}
$reference = $value;
unset($reference);

var_dump($array);

如果您必须在这样的字符串中定义一系列键,那么只需使用可以分解的简单分隔符就更简单了,而不需要修剪以构建单个键的数组,所以更简单的像abc[a][b][c]

If you have to define a sequence of keys in a string like this, then it's simpler just to use a simple separator that can be exploded rather than needing to trim as well to build an array of individual keys, so something simpler like a.b.c would be easier to work with than [a][b][c]

演示

这篇关于PHP:使用变量作为键设置嵌套数组的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆