PHP: Set value of nested array using variable as k

2019-01-20 17:10发布

问题:

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

回答1:

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



回答2:

Easiest way to do this would be using this library:

Arr::handleNestedElement($array, 'a.b.c', 'new_value');

alternatively if you have keys as array you can use this form:

Arr::handleNestedElement($array, ['a', 'b', 'c'], 'new_value');


回答3:

Hi bro you can do it like this throught an array of keys :

This is your array structured :

$array = array(
    'a'=> array(
        'b' => array(
            'c'=>'some value',
        ),
    ),
);

This is the PHP code to get value from your array with dynamic keys :

$result = $array; //Init an result array by the content of $array

$keys = array('a','b','c'); //Make an array of keys

//For loop to get result by keys
for($i=0;$i<count($keys);$i++){
    $result = $result[$keys[$i]];
}

echo $result; // $result = 'new value'

I hope that the answer help you, Find here the PHPFiddle of your working code.