我需要一个像这样的功能:
function multi(){
$args = get_func_args();
$array = ????
return $array;
}
print_r(multi('foo','bar','baz',123));
// expected result: array([foo] => array([bar] => array([baz] => 123)))
答案 0 :(得分:1)
我已经使用构建数组的引用回答了这个问题的多种变体:
function multi() {
$path = func_get_args(); //get args
$value = array_pop($path); //get last arg for value
$result = array(); //define our result
$temp = &$result; //reference our result
//loop through args to create key
foreach($path as $key) {
//assign array as reference to and create new inner array
$temp =& $temp[$key];
}
$temp = $value; //set the value
return $result;
}
print_r(multi('foo','bar','baz',123));
答案 1 :(得分:0)
这也有效:
function multi(){
$array = null;
$args = func_get_args();
while(count($args)>0) {
$last = array_pop($args);
$array = $array ? array($last=>$array) : $last;
}
return $array;
}
$data = multi('foo','bar','baz',123);
更新现有值(不检查项目是否确实存在)
function set_multi($val, &$target){
$args = array_slice(func_get_args(), 2);
while(count($args)>0) {
$first = array_shift($args);
$target = &$target[$first];
}
$target = $val;
}
set_multi(456, $data, 'foo', 'bar', 'baz');