如何通过键名/路径访问和操作多维数组?我必须实现一个塞特在PHP中,这允许我指定数组(目标)的键或子键,将名称作为点分隔的键值传递。鉴于以下代码:$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);$key = 'b.x.z';$path = explode('.', $key);从…的价值$key我想达到这个价值5的$arr['b']['x']['z'].现在,给定的变量值为$key不同的$arr价值(具有不同的深度)。如何设置$key?为吸气剂 get()我写了这段代码: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;}写一个塞特是比较困难的,因为我成功地找到了正确的元素(从$key),但我无法在原始数组中设置值,也不知道如何一次性指定键。我应该使用某种回溯吗?或者我能避开它吗?
3 回答
倚天杖
TA贡献1828条经验 获得超3个赞
$pathexplode$pathisset):
$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');Unsetter
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;}
慕后森
TA贡献1802条经验 获得超5个赞
$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);$key = 'b.x.z';$path = explode('.', $key);print_r(Arrays::getNestedValue($arr, $path));$arr = array('a' => 1,
'b' => array(
'y' => 2,
'x' => array('z' => 5, 'w' => 'abc')
),
'c' => null);Arrays::setNestedValue($arr, array('d', 'e', 'f'), 'value');print_r($arr);- 3 回答
- 0 关注
- 480 浏览
添加回答
举报
0/150
提交
取消
