Access nested associative array by array of string

2019-09-16 21:35发布

问题:

So basically i would like to transform code like

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

To something like:

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

I tried something like:

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

    $current = $current[ $cur ];
}

$current[$k] = $v;

But I know this code isn't supposed to work.. How can I do this? I don't know exact level of nesting in $cur_string array.

回答1:

You can use the following method which is based on passing by reference.

/**
 * 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);
}

Usage:

Without initial value:

$a = [];

saveByPath($a, [1, 2, 3, 4], 'value');

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

With initial value:

$a = [];
$a[1][2][3][4] = 'initialValue';

saveByPath($a, [1, 2, 3, 4], 'value');

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


回答2:

Showing both set and get functions:

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