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

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

问题描述

可以说我有这样的code的:

  $阵列= [
        'A'=> [
            'B'=> [
                'C'=>'某个值',
            ]
        ]
    ];    $阵列['一'] ['B'] ['C'] ='新价值;

当然,这是工作,但我想要的是采用可变,这样的事情来更新这个C键:

  $键='[A] [B] [C]';
$数组{$}键='新的价值;

但键treatening为字符串,这是我所得到的:

  $阵列[[A] [B] [C]'] ='新价值;

所以我想一些帮助,给我以正确的方式来完成这项工作,而无需使用eval()函数。

顺便说一句,可以有任意数量的阵列巢,所以这样的事情是不是一个很好的答案:

  $键1 ='A';
$键2 ='B​​';
$ KEY3 ='C';
$阵列[$键1] [$密钥2] [$ KEY3] ='新价值;


解决方案

这不是定义你的钥匙的最好方式,但是:

  $阵列= [];
$键='[A] [B] [C]';
$值='HELLO WORLD;$键=爆炸('] [',修剪($键,[]));
$参考=安培; $阵列;
的foreach($键为$键){
    如果(!array_key_exists($键,$参考)){
        参考$ [$关键] = [];
    }
    $参考=&放大器; $参考[$关键];
}
$基准= $价值;
未设置($参考);后续代码var_dump($数组);

如果你有一个像这样的字符串来定义键序列,那么它的简单只是使用简单的分离,可以发生爆炸而不需要修剪,以及建立独立按键阵列,这样更简单的东西像 ABC 会更容易一起工作[A] [b] [C]

演示

Lets say i have this kind of code:

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

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

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';

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);

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]

Demo

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

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