使用字符串访问(可能很大)多维数组
我无法找到一种方法来简单地解析字符串输入并在多维数组中找到正确的位置。
我希望用一两行代码来完成此操作,因为我看到的解决方案依赖于长(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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
考虑到
$vars
是您希望获得one['one-one']
或two['two-two']['more'] 的变量
from (Demo):这是将字符串词法分析为key 标记,然后遍历
$vars
数组位于键控值上,而$vars
数组已转换为函数。旧的东西:
使用仅 eval 的函数重载数组:
如果您不喜欢 eval,请更改实现:
Considering
$vars
being your variables you would like to getone['one-one']
ortwo['two-two']['more']
from (Demo):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:
If you're not a fan of eval, change the implementation:
怎么样
How about
其一,您的
get()
函数中没有$var
。 $var 是在函数外部定义的,PHP 作用域规则不会使“较高”的变量在较低的作用域中可见,除非在较低的作用域中显式地设置为全局:可能有效,但这没有经过测试,并且使用 eval 几乎总是一个非常好的选择。坏主意。
For one, you've not got a
$var
in yourget()
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:might work, but this isn't tested, and using eval is almost always a very bad idea.
Kohana 有一个很好的 Config 类,它允许这样的事情:
您可以在这里查看:http:// kohanaframework.org/3.1/guide/api/Config
Kohana has a nice Config class which alows something like this:
You can check it out here: http://kohanaframework.org/3.1/guide/api/Config