通过字符串数组访问嵌套的关联数组


Access nested associative array by array of strings

所以基本上我想像这样转换代码

$my_array = [];   
$cur_string = ['a', 'b', 'c', 'd'];
$v = 'Hello world!';

像这样:

$my_array['a']['b']['c']['d'] = $v;

我尝试了类似的东西:

foreach( $cur_string as $cur ) {
    if ( !isset( $current[ $cur ] ) ) {
        $current[ $cur ] = [];
    }
    $current = $current[ $cur ];
}
$current[$k] = $v;

但我知道这段代码不应该工作。我该怎么做?我不知道 $cur_string 数组中的确切嵌套级别。

您可以使用以下基于引用传递的方法。

/**
 * Fill array element with provided value by given path
 * @param array $data Initial array
 * @param array $path Keys array which transforms to path
 * For example, [1, 2, 3] transforms to [1][2][3]
 * @param mixed $value Saved value
 */
function saveByPath(&$data, $path, $value)
{
    $temp = &$data;
    foreach ($path as $key) {
        $temp = &$temp[$key];        
    }
    // Modify only if there is no value by given path in initial array
    if (!$temp) {
        $temp = $value;
    }
    unset($temp);
}

用法:

没有初始值:

$a = [];
saveByPath($a, [1, 2, 3, 4], 'value');
var_dump($a[1][2][3][4]) -> 'value';

初始值:

$a = [];
$a[1][2][3][4] = 'initialValue';
saveByPath($a, [1, 2, 3, 4], 'value');
var_dump($a[1][2][3][4]) -> 'initialValue';

显示设置和获取函数:

$my_array = [];   
$cur_string = ['a', 'b', 'c', 'd'];
$cur_string2 = ['a', 'b', 'd', 'e'];
$v = 'Hello world!';
$v2 = 'Hello world2!';
function setValue(&$array, $position, $value) {
    $arrayElement = &$array;
    foreach($position as $index) {
        $arrayElement = &$arrayElement[$index];
    }
    $arrayElement = $value;
}
function getValue($array, $position) {
    $arrayElement = $array;
    foreach($position as $index) {
        if(!isset($arrayElement[$index])) {
            throw new Exception('Element is not set');
        }
        $arrayElement = $arrayElement[$index];
    }
    return $arrayElement;
}
setValue($my_array, $cur_string, $v);
setValue($my_array, $cur_string2, $v2);
var_dump($my_array);
try {
    $result = getValue($my_array, $cur_string);
} catch(Exception $e) {
    die($e->getMessage);
}
var_dump($result);