一尘不染

使用字符串访问(可能很大)多维数组

php

我在想办法简单地分析字符串输入并在多维数组中找到正确的位置时遇到了麻烦。

我希望有一到两行能够做到这一点,因为我看到的解决方案依赖于较长的(10-20行)循环。

考虑下面的代码(注意,嵌套 可能 ,理论上是任意深度的):

function get($string)
{
    $vars = array(
        'one' => array(
            'one-one' => "hello",
            'one-two' => "goodbye"
        ),
        'two' => array(
            'two-one' => "foo",
            'two-two' => "bar"
        )
    );

    return $vars[$string]; //this syntax isn't required, just here to give an idea
}

get("two['two-two']");  //desired output: "bar".  Actual output: null

是否可以简单地使用内置函数或其他易于重新创建所需输出的函数?


阅读 261

收藏
2020-05-29

共1个答案

一尘不染

考虑$vars为您的变量,你想获得one['one-one']two['two- two']['more']从(演示):

$vars = function($str) use ($vars)
{
    $c = function($v, $w) {return $w ? $v[$w] : $v;};
    return array_reduce(preg_split('~\[\'|\'\]~', $str), $c, $vars);
};
echo $vars("one['one-one']"); # hello
echo $vars("two['two-two']['more']"); # tea-time!

这是乐星串入 密钥 令牌,然后遍历$vars在阵列 带键 的值,而$vars阵列已变成了功能。


旧资料:

用一个只是eval的函数重载数组:

$vars = array(
    'one' => array(
        'one-one' => "hello",
        'one-two' => "goodbye"
    ),
    'two' => array(
        'two-one' => "foo",
        'two-two' => "bar"
    )
);

$vars = function($str) use ($vars)
{
    return eval('return $vars'.$str.';');
};

echo $vars("['one']['one-two']"); # goodbye

如果您不喜欢eval,请更改实现:

$vars = function($str) use ($vars)
{
    $r = preg_match_all('~\[\'([a-z-]+)\']~', $str, $keys);
    $var = $vars;
    foreach($keys[1] as $key)
        $var = $var[$key];
    return $var;
};
echo $vars("['one']['one-two']"); # goodbye
2020-05-29