我很难找到一种方法来简单地解析字符串输入并在多维数组中找到正确的位置。
我希望有一到两行来做到这一点,因为我见过的解决方案依赖于长(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
是否有一个简单的使用内置函数或其他简单的东西,将重新创建我想要的输出?
考虑到$vars
是您的变量,您希望从(Demo)中获得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
$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 );
首先,您的get()
函数中没有$var
。$var是在函数外部定义的,PHP的作用域规则不会让"高级"变量在低级作用域中可见,除非在低级作用域中显式地设置为全局:
function get($string) {
global $vars;
eval('$x = $vars' . $string);
return $x;
}
get("['two']['two-two']");
可能有效,但没有经过测试,使用eval几乎总是一个非常糟糕的主意。
Kohana有一个很好的Config类,它允许这样做:
echo Config::get("two.two-two");
你可以在这里查看:http://kohanaframework.org/3.1/guide/api/Config