发布具有相同名称属性的表单字段 [英] POSTing Form Fields with same Name Attribute

查看:29
本文介绍了发布具有相同名称属性的表单字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您的表单包含具有重复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.

这篇关于发布具有相同名称属性的表单字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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