假设已经是一个数组 via (或 add to the function),那么你可以使用引用。您需要添加一些错误检查,以防无效等(想想):$path
explode
$path
isset
$key = 'b.x.z';
$path = explode('.', $key);
吸气剂
function get($path, $array) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
return $temp;
}
$value = get($path, $arr); //returns NULL if the path doesn't exist
设置者/创建者
此组合将在现有数组中设置一个值,或者如果传递一个尚未定义的数组,则创建该数组。确保定义要通过引用传递:$array
&$array
function set($path, &$array=array(), $value=null) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($path, $arr);
//or
set($path, $arr, 'some value');
解调器
这将是路径中的最后一个键:unset
function unsetter($path, &$array) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
if(!is_array($temp[$key])) {
unset($temp[$key]);
} else {
$temp =& $temp[$key];
}
}
}
unsetter($path, $arr);
*原始答案有一些有限的功能,我会留下,以防它们对某人有用:
二传手
确保定义要通过引用传递:$array
&$array
function set(&$array, $path, $value) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($arr, $path, 'some value');
或者,如果您想返回更新的数组(因为我很无聊):
function set($array, $path, $value) {
//$path = explode('.', $path); //if needed
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
return $array;
}
$arr = set($arr, $path, 'some value');
造物主
如果您不想创建数组并选择性地设置值:
function create($path, $value=null) {
//$path = explode('.', $path); //if needed
foreach(array_reverse($path) as $key) {
$value = array($key => $value);
}
return $value;
}
$arr = create($path);
//or
$arr = create($path, 'some value');
为了好玩
构造并计算类似给定字符串的内容:$array['b']['x']['z']
b.x.z
function get($array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$result = \$array{$path};");
return $result;
}
设置类似下面的内容:$array['b']['x']['z'] = 'some value';
function set(&$array, $path, $value) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("\$array{$path} = $value;");
}
取消设置类似以下内容的内容:$array['b']['x']['z']
function unsetter(&$array, $path) {
//$path = explode('.', $path); //if needed
$path = "['" . implode("']['", $path) . "']";
eval("unset(\$array{$path});");
}