如何编写的getter / setter通过按键名称访问的多级阵列? [英] How to write getter/setter to access multi-level array by key names?

查看:133
本文介绍了如何编写的getter / setter通过按键名称访问的多级阵列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现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']

现在....
$键和不同的 $改编值(不同深度)的变量值。

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);

设置器

请确保定义 $阵列来按引用传递&放大器; $阵列

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');

这篇关于如何编写的getter / setter通过按键名称访问的多级阵列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆