PHP的通话从字符串数组 [英] php call array from string

查看:120
本文介绍了PHP的通话从字符串数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含数组元素的字符串。

I have a string that contains elements from array.

$str = '[some][string]';
$array = array();

我如何获得 $数组的值['一些'] ['字符串'] 使用 $ STR

推荐答案

您可以通过使用eval这样做,不知道你舒服:

You can do so by using eval, don't know if your comfortable with it:

$array['some']['string'] = 'test';    
$str = '[some][string]';    
$code = sprintf('return $array%s;', str_replace(array('[',']'), array('[\'', '\']'), $str));    
$value = eval($code);    
echo $value; # test

不过EVAL并不总是正确的工具,因为还有,它表明最常你有一个设计缺陷,当你需要使用它。

However eval is not always the right tool because well, it shows most often that you have a design flaw when you need to use it.

另外一个例子,如果你需要写访问阵列项目,您可以执行以下操作:

Another example if you need to write access to the array item, you can do the following:

$array['some']['string'] = 'test';
$str = '[some][string]';
$path = explode('][', substr($str, 1, -1));
$value = &$array;
foreach($path as $segment)
{
    $value = &$value[$segment];
}

echo $value;
$value = 'changed';
print_r($array);

这实际上是相同的原则,在 Eric的答案,但引用变量。

This is actually the same principle as in Eric's answer but referencing the variable.

这篇关于PHP的通话从字符串数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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