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

时间:2015-03-08 12:33:02

标签: php arrays indexing nested

所以基本上我想转换像

这样的代码
$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数组中嵌套的确切级别。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

显示set和get函数:

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