我已经实现一个二传手在PHP中,这让我可以指定一个阵列(目标)的键或子键,通过这个名字作为一个点分隔的项值。
I've to implement a setter in PHP, that allows me to specify the key, or sub key, of an array (the target), passing the name as a dot-separated-keys value.
由于以下code:
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);
$key = 'b.x.z';
$path = explode('.', $key);
从 $键
我想达到的值 5 的值 $改编['B'] ['X'] ['Z']
。
From the value of $key
I want to reach the value 5 of $arr['b']['x']['z']
.
现在....
鉴于 $键
及不同的 $改编
值(用不同的深度)的变量值。
Now....
given a variable value of $key
and a different $arr
value (with different deepness).
对于的getter 的的get()
我写这篇code:
For the getter get()
I wrote this code:
public static function get($name, $default = null)
{
$setting_path = explode('.', $name);
$val = $this->settings;
foreach ($setting_path as $key) {
if(array_key_exists($key, $val)) {
$val = $val[$key];
} else {
$val = $default;
break;
}
}
return $val;
}
要编写的二传手的是比较困难的,因为我成功达到合适的元素(从 $键
),但我不能够设置原始数组中的价值,我不知道如何指定密钥的一次。
To write a setter is more difficult cause I succeed in reaching the right element (from the $key
), but I am not able to set the value in the original array and I don't know how to specify the key all at once.
我应该使用某种回溯?或者,我可以避开它?
Should I use some kind of backtracking? Or can I avoid it?
假设 $ PATH
已通过阵列爆炸
,使用引用。你需要一些错误检查的情况下无效 $路径添加
等等...
Assuming $path
is already an array via explode
, use references. You need to add in some error checking in case of invalid $path
etc...
$key = 'b.x.z';
$path = explode('.', $key);
function get($array, $path) {
$temp = &$array;
foreach($path as $key) {
$temp =& $temp[$key];
}
return $temp;
}
$value = get($arr, $path);
请确保定义 $阵列
来通过引用传递&放大器; $阵列
:
Make sure to define $array
to be passed by reference &$array
:
function set(&$array, $path, $value) {
$temp = &$array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
}
set($arr, $path, 'some value');
或者,如果你想返回更新数组(因为我很无聊):
Or if you want to return the updated array (because I'm bored):
function set($array, $path, $value) {
$temp = &$array;
foreach($path as $key) {
$temp =& $temp[$key];
}
$temp = $value;
return $array;
}
$arr = set($arr, $path, 'some value');