假设
$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);//orset($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});");}


