我有一个像这样的字符串:
$string = 'one/two/three/four';
我把它变成一个数组:
$keys = explode('/', $string);
该数组可以有任意数量的元素,例如 1、2、5 等。
如何为多维数组分配某个值,但使用$keys
我上面创建的时候要确定插入到哪里的位置?
Like:
$arr['one']['two']['three']['four'] = 'value';
抱歉,如果问题令人困惑,但我不知道如何更好地解释它
这有点不简单,因为你想要嵌套,但它应该是这样的:
function insert_using_keys($arr, $keys, $value){
// we're modifying a copy of $arr, but here
// we obtain a reference to it. we move the
// reference in order to set the values.
$a = &$arr;
while( count($keys) > 0 ){
// get next first key
$k = array_shift($keys);
// if $a isn't an array already, make it one
if(!is_array($a)){
$a = array();
}
// move the reference deeper
$a = &$a[$k];
}
$a = $value;
// return a copy of $arr with the value set
return $arr;
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)