我想编写一个修改数组的函数:
function addDataToArray($array,array("data","userdata","username"),"john") { // do something here }
结果将是$ array ["数据"] [" userdata"] ["用户名"] =" john"
我意识到以正常方式实现这一目标要容易得多,但我需要了解是否可以这样做。 感谢
答案 0 :(得分:1)
此代码应该适合您。我有点受到question的启发:
function addDataToArray(&$array,$input_array,$string) {
$count = count($input_array)-1;
$tmp = array($input_array[$count]=>$string);
for ($i=$count-1;$i>=0;$i--) {
$arr = array();
$arr[$input_array[$i]] = $tmp;
$tmp = $arr;
}
$array = array_merge($array, $arr);
}
$array = array(); //or your inicialized $array
addDataToArray($array,array("data","userdata","username"),"john");
var_dump($array);
答案 1 :(得分:1)
使用递归
$array = array("foo" => "bar");
function addDataToArray(&$a, $path, $val)
{
if (count($path) == 1) {
$path = $path[0];
}
if (!is_array($path)) {
$a[$path] = $val;
return $a;
}
$b = array();
$a[array_shift($path)] = addDataToArray($b, $path, $val);
return $a;
}
addDataToArray($array, array("data","userdata","username"),"john");
var_dump($array);
结果
array(2) {
["foo"]=>
string(3) "bar"
["data"]=>
array(1) {
["userdata"]=>
array(1) {
["username"]=>
string(4) "john"
}
}
}