如何使用字符串获取PHP中关联HTML数组的值? [英] How to get value of an associative HTML array in PHP using a string?
问题描述
看我有这样的表格:
<form method="post">
<input name="variable[var1][var2]" value="44"/>
</form>
我想使用类似这样的字符串来获取PHP中variable[var1][var2]
的值:
I want to get the value of variable[var1][var2]
in PHP using a string like:
$str = "['variable']['var1']['var2']";
echo "{$_POST{$str}}";
为什么我需要这样做?
我需要它,因为获取该值的代码是完全动态的,并且我无法使用$_POST['variable']['var1']['var2']
手动获取或设置该值.
I need it because the code that gets the value is totally dynamic and I cannot get or set manually the value using $_POST['variable']['var1']['var2']
.
你能帮忙吗?
注意:我知道可以使用$_POST['variable']['var1']['var2']
来获得它,请不要问我为什么不使用这种方式.我只需要使用上述方法(使用$str
).
NOTE: I know this is possible to get it using $_POST['variable']['var1']['var2']
, please don't ask me about why I'm not using this way. Simply I need to use as above (using $str
).
推荐答案
您可以使用preg_match_all()
将字符串中的所有索引放入数组:
You can use preg_match_all()
to get all the indexes in the string into an array:
$indexes = preg_match_all('/(?<=\[\')(?:[^\']*)(?=\'\])/', $str);
$indexes = $indexes[0]; // Get just the whole matches
然后使用循环钻入$_POST
.
$cur = $_POST;
foreach ($indexes as $index) {
$cur = $cur[$index];
}
此时$cur
将包含您想要的值.
At this point $cur
will contain the value you want.
这篇关于如何使用字符串获取PHP中关联HTML数组的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!