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

发布于 2024-11-29 00:59:52 字数 622 浏览 0 评论 0原文

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

我希望用一两行代码来完成此操作,因为我看到的解决方案依赖于长(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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

鲜血染红嫁衣 2024-12-06 00:59:52

考虑到 $vars 是您希望获得 one['one-one']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 标记,然后遍历$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

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!

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.


Older Stuff:

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

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
北笙凉宸 2024-12-06 00:59:52

怎么样

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

function get( $string, $vars )
{
    $keys = explode( '][', substr( $string, 1, -1 ) );
    foreach( $keys as $key ) {
        $vars = $vars[$key];
    }
    return $vars;
}

echo get( '[two][two-one]', $vars );

How about

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

function get( $string, $vars )
{
    $keys = explode( '][', substr( $string, 1, -1 ) );
    foreach( $keys as $key ) {
        $vars = $vars[$key];
    }
    return $vars;
}

echo get( '[two][two-one]', $vars );
梦里寻她 2024-12-06 00:59:52

其一,您的 get() 函数中没有 $var 。 $var 是在函数外部定义的,PHP 作用域规则不会使“较高”的变量在较低的作用域中可见,除非在较低的作用域中显式地设置为全局:

function get($string) {
   global $vars;
   eval('$x = $vars' . $string);
   return $x;
}

get("['two']['two-two']");

可能有效,但这没有经过测试,并且使用 eval 几乎总是一个非常好的选择。坏主意。

For one, you've not got a $var in your get() function. $var was defined outside the function, and PHP scoping rules do not make "higher" vars visible in lower scopes unless explictly made global in the lower scope:

function get($string) {
   global $vars;
   eval('$x = $vars' . $string);
   return $x;
}

get("['two']['two-two']");

might work, but this isn't tested, and using eval is almost always a very bad idea.

过潦 2024-12-06 00:59:52

Kohana 有一个很好的 Config 类,它允许这样的事情:

echo Config::get("two.two-two");

您可以在这里查看:http:// kohanaframework.org/3.1/guide/api/Config

Kohana has a nice Config class which alows something like this:

echo Config::get("two.two-two");

You can check it out here: http://kohanaframework.org/3.1/guide/api/Config

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文