【发布时间】:2016-04-06 15:27:14
【问题描述】:
我有一个包含 8 个字段的表单。我用这样的 for 循环创建了这个表单:
echo '<form name="num" method="post">';//create a form that uses the POST method for submission
for($i=0; $i<8; $i++){//loop 8 times, and display 8 input fields
echo '<input id='.$i.' type="number" name="num[]" >';
}
echo '<input type="submit" class="submit" name="num-submit" value="Go">
</form>';
我想遍历所有这些字段,获取用户提交的数字,并对这些值进行一些算术运算。
我在堆栈溢出中查看了与我类似的其他问题;我已经尝试过 Marc B 的回复:
"
给定:
<input type="text" name="foo[]" />
<input type="text" name="foo[]" />
等等...在你的表单中,你会用
循环它们
foreach($_POST['foo'] as $index => $value) {
... }
"
我已将该响应应用于我自己的代码:
if (!empty($_POST['num-submit'])) {//If the form is submitted, execute the following code
foreach($_POST['num'] as $name => $value) {// Loop over each item in the form.
//code to add elements (the numbers submitted) together
}
}
这完全适合我,但我只是不明白为什么这是解决方案。我想完整解释为什么这是解决方案以及为什么输入字段的名称必须是 foo[] 或 num[] 并带有方括号(这不只是创建一个数组吗?)。此外,如果您还可以帮助在该循环中将数字相加,那就太好了。
提前非常感谢!
【问题讨论】:
标签: php arrays forms loops post