使用字符串来访问(可能很大)多维数组 [英] use strings to access (potentially large) multidimensional arrays
问题描述
我无法找出一种方法来简单解析字符串输入,并找到一个多维数组中的正确位置。
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?
推荐答案
考虑 $瓦尔
为您的变量,你想获得单['一对一']
或双['两进两出'] ['更多']
从(的演示):
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.
的旧的东西:的
重载阵列功能,只是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屋!