通过字符串数组访问嵌套的关联数组 [英] Access nested associative array by array of strings
本文介绍了通过字符串数组访问嵌套的关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
所以基本上我想转换类似的代码
So basically i would like to transform code like
$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数组中嵌套的确切级别.
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.
推荐答案
您可以使用以下基于引用传递的方法.
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);
}
用法:
没有初始值:
$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';
这篇关于通过字符串数组访问嵌套的关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文