假设
$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
Setter / Creator
这个组合将在现有的数组中设置一个值,或者如果你传递一个尚未定义的数组,则创建该数组。请确保定义$array
作为引用传递&$array
:
function set($path, &$array=array(), $value=null) {
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($path, $arr);
set($path, $arr, 'some value');
Unsetter
这将会取消设定路径中的最终键值:
function unsetter($path, &$array) {
$temp =& $array;
foreach($path as $key) {
if(!is_array($temp[$key])) {
unset($temp[$key]);
} else {
$temp =& $temp[$key];
}
}
}
unsetter($path, $arr);
*原始答案有一些有限的功能,我将保留以防它们对某人有用:
Setter
请确保定义要传递的$array
是引用&$array
:
function set(&$array, $path, $value) {
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($arr, $path, 'some value');
或者如果您想返回更新后的数组(因为我感到无聊):
function set($array, $path, $value) {
$temp =& $array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
return $array;
}
$arr = set($arr, $path, 'some value');
创建者
如果你想创建一个数组并可选地设置值:
function create($path, $value=null) {
foreach(array_reverse($path) as $key) {
$value = array($key => $value);
}
return $value;
}
$arr = create($path);
$arr = create($path, 'some value');
有趣的事情
根据字符串b.x.z
,构建并评估类似于$array['b']['x']['z']
的内容:
function get($array, $path) {
$path = "['" . implode("']['", $path) . "']";
eval("\$result = \$array{$path};");
return $result;
}
设置类似于
$array ['b'] ['x'] ['z'] ='一些值';
的东西:
function set(&$array, $path, $value) {
$path = "['" . implode("']['", $path) . "']";
eval("\$array{$path} = $value;");
}
取消类似于$array['b']['x']['z']
的设置:
function unsetter(&$array, $path) {
$path = "['" . implode("']['", $path) . "']";
eval("unset(\$array{$path});");
}