如何写的getter / setter访问多层次的数组点分隔的键名?数组、多层次、如何写、键名

2023-09-10 22:36:29 作者:煙花落后ぃ一片哀傷づ

我已经实现一个二传手在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);

Setter方法​​

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

Setter

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