POSTing Form Fields with same Name Attribute(发布具有相同名称属性的表单字段)
问题描述
如果您的表单包含具有重复name 属性的文本输入,并且该表单已发布,您是否仍然能够从$_POST获取所有字段的值?代码> PHP 中的数组?
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>
请参阅 Sitepoint 上的 HTML 参考.
See the HTML reference at Sitepoint.
如果不使用 [],$_POST 将只包含最后一个值的原因是因为 PHP 基本上只会在原始查询字符串上爆炸和 foreach填充 $_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.
这篇关于发布具有相同名称属性的表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:发布具有相同名称属性的表单字段
基础教程推荐
- 如何在 Laravel 中使用 React Router? 2022-01-01
- PHP PDO MySQL 查询 LIKE ->多个关键词 2021-01-01
- PHP 类:全局变量作为类中的属性 2021-01-01
- 如何替换eregi() 2022-01-01
- 有什么方法可以用编码 UTF-8 而不是 Unicode 返回 PHP`json_encode`? 2021-01-01
- 在PHP中根据W3C规范Unicode 2022-01-01
- YouTube API v3 点赞视频,但计数器不增加 2022-01-01
- 学说 dbal querybuilder 作为准备好的语句 2022-01-01
- Cron Jobs 调用带有变量的 PHP 脚本 2022-01-01
- 如何在 Laravel 5.3 注册中添加动态下拉列表列? 2021-01-01
