分配给任意深度的数组索引? [英] Assign to an arbitrarily deep array index?
本文介绍了分配给任意深度的数组索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有对应于另一个数组先后递归按键阵列,什么是一个值分配到路径的最佳方式(如果你想这样称呼它)?
If I have an array which corresponds to successively recursive keys in another array, what is the best way to to assign a value to that "path" (if you want to call it that)?
例如:
$some_array = array();
$path = array('a','b','c');
set_value($some_array,$path,'some value');
现在, $ some_array
应该等于
array(
'a' => array(
'b' => array(
'c' => 'some value'
)))
目前,我使用以下内容:
At the moment, I am using the following:
function set_value(&$dest,$path,$value) {
$addr = "\$dest['" . implode("']['", $path) . "']";
eval("$addr = \$value;");
}
显然,这是一个非常幼稚的做法,会带来安全隐患,所以你会怎么做呢?
Obviously, this is a very naive approach and poses a security risk, so how would you do it?
推荐答案
递归解决方案(未测试):
Recursive solution (not tested):
function set_value(&$dest,$path,$value) {
$index=array_shift($path);
if(empty($path)){
// on last level
$dest[$index]=$value;
}
else{
// descending to next level
set_value($dest[$index],$path,$value);
}
}
这篇关于分配给任意深度的数组索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文