具有相同名称属性的过帐表单字段 [英] POSTing Form Fields with same Name Attribute
问题描述
如果您有一个包含带有重复的name
属性的文本输入的表单,并且该表单已过帐,您仍然能够从PHP的$_POST
数组中获取所有字段的值吗?
If you have a form containing text inputs with duplicate name
attributes, and the form is posted, will you still be able to obtain the values of all fields from the $_POST
array in PHP?
推荐答案
否.仅最后一个输入元素可用.
No. Only the last input element will be available.
如果要使用相同名称的多个输入,请使用name="foo[]"
作为输入名称属性. $_POST
随后将包含foo的数组,其中包含来自输入元素的所有值.
If you want multiple inputs with the same name use name="foo[]"
for the input name attribute. $_POST
will then contain an array for foo with all values from the input elements.
<form method="post">
<input name="a[]" value="foo"/>
<input name="a[]" value="bar"/>
<input name="a[]" value="baz"/>
<input type="submit" />
</form>
请参阅站点上的HTML参考.
如果不使用[]
,为什么$_POST
仅包含最后一个值,是因为PHP基本上只会爆炸并遍历原始查询字符串以填充$_POST
.当遇到已经存在的名称/值对时,它将覆盖前一个.
The reason why $_POST
will only contain the last value if you don't use []
is because PHP will basically just explode and foreach over the raw query string to populate $_POST
. When it encounters a name/value pair that already exists, it will overwrite the previous one.
但是,您仍然可以像这样访问原始查询字符串:
However, you can still access the raw query string like this:
$rawQueryString = file_get_contents('php://input'))
假设您具有这样的表单:
Assuming you have a form like this:
<form method="post">
<input type="hidden" name="a" value="foo"/>
<input type="hidden" name="a" value="bar"/>
<input type="hidden" name="a" value="baz"/>
<input type="submit" />
</form>
$ rawQueryString
将包含a=foo&a=bar&a=baz
.
然后,您可以使用自己的逻辑将其解析为数组.天真的方法是
You can then use your own logic to parse this into an array. A naive approach would be
$post = array();
foreach (explode('&', file_get_contents('php://input')) as $keyValuePair) {
list($key, $value) = explode('=', $keyValuePair);
$post[$key][] = $value;
}
这将为您提供查询字符串中每个名称的数组数组.
which would then give you an array of arrays for each name in the query string.
这篇关于具有相同名称属性的过帐表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!