PHP: Set value of nested array using variable as key

后端 未结 3 1482
情歌与酒
情歌与酒 2020-12-11 07:28

Lets say i have this kind of code:

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


        
3条回答
  •  不知归路
    2020-12-11 08:00

    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

提交回复
热议问题