使用字符串访问(可能很大)多维数组 [英] use strings to access (potentially large) multidimensional arrays

查看:32
本文介绍了使用字符串访问(可能很大)多维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我无法找到一种方法来简单地解析字符串输入并在多维数组中找到正确的位置.

I am having trouble figuring out a way to simply parse a string input and find the correct location within a multidimensional array.

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

I am hoping for one or two lines to do this, as the solutions I have seen rely on long (10-20 line) loops.

给定以下代码(请注意,理论上,嵌套可以具有任意深度):

Given the following code (note that the nesting could, in theory, be of any arbitrary depth):

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

是否可以简单地使用内置函数或其他简单的方法来重新创建我想要的输出?

Is there a simple use of built-in functions or something else easy that would recreate my desired output?

推荐答案

考虑到 $vars 是你想要获得的变量 one['one-one']two['two-two']['more'] 来自 (Demo):

Considering $vars being your variables you would like to get one['one-one'] or two['two-two']['more'] from (Demo):

$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!

这是将字符串词法转换为 key 标记,然后在 keyed 值上遍历 $vars 数组,而 $vars 数组已经变成了一个函数.

This is lexing the string into key tokens and then traverse the $vars array on the keyed values while the $vars array has been turned into a function.

旧的东西:

使用仅 eval 的函数重载数组:

Overload the array with a function that just eval's:

$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,请更改实现:

If you're not a fan of eval, change the implementation:

$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

这篇关于使用字符串访问(可能很大)多维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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