【问题标题】:PHP foreach loop with form data [closed]带有表单数据的PHP foreach循环[关闭]
【发布时间】:2014-03-18 18:44:38
【问题描述】:

我正在尝试通过 php 从 html 表单中获取数据,并为每个输入循环 x 次。

这是代码:

    foreach ($_GET['first_input_field'] as $val)
{
$temp_second_field = $_GET['second_input_field'][$value];
for ($i = 0 ; $i <= $temp_second_field ; $i++)
{

echo $val;

   }
$i=0;
}

形式:

<input type="text" name="first_input_field[1]" id="field_1" value="Text 1"><input type="number" name="second_input_field[1]" min="1" max="4">
<input type="text" name="first_input_field[2]" id="field_2" value="Text 1"><input type="number" name="second_input_field[2]" min="1" max="4">
<input type="text" name="first_input_field[x]" id="field_x" value="Text 1"><input type="number" name="second_input_field[x]" min="1" max="4">

表单有一个 + 按钮,用于添加两个字段(自动增加 first_input_field 和 second_input_field 编号)。

我正在尝试将 first_input_field 值重复 x 次,其中 x 是 second_input_field 值 然后回显它。

但我在这里得到未定义的索引:错误。 $temp_second_field = $_GET['second_input_field'][$value];

提前求助。

【问题讨论】:

  • 如果我理解你的话,我认为你只需要将 $val 切换为 $value 或反之亦然
  • 你的&lt;form&gt;标签的方法是什么?

标签: php html arrays forms foreach


【解决方案1】:

尝试改变

$temp_second_field = $_GET['second_input_field'][$value];

$temp_second_field = $_GET['second_input_field'][$val];

【讨论】:

    【解决方案2】:

    不要在 HTML 元素名称中输入数字:

    <input type="text" name="first_input_field[]" id="field_1" value="Text 1"><input type="number" name="second_input_field[]" min="1" max="4">
    <input type="text" name="first_input_field[]" id="field_2" value="Text 1"><input type="number" name="second_input_field[]" min="1" max="4">
    <input type="text" name="first_input_field[]" id="field_x" value="Text 1"><input type="number" name="second_input_field[]" min="1" max="4">
    

    编辑:除此之外,您正在使用代码中未设置的 $value 循环遍历事物,实际上不需要 for 循环:

    foreach ($_GET['first_input_field'] as $k=>$val) {
        $count = $_GET['second_input_field'][$k];
        str_repeat($val, $count);
    }
    

    【讨论】:

    • 就是这样!非常感谢
    • 不客气。我已经编辑以消除对内部循环的需要。
    • 当你在这里时,我现在有第二个问题 :) echo $val 。 '0,30';这个 0,30 应该在每次 echo 以某个确切的数字(如 +30)解析时上升,所以 30,60
    • 爆炸、增量和内爆。如果您需要更多解释,请打开一个新问题。
    猜你喜欢
    • 2012-05-02
    • 1970-01-01
    • 2014-01-26
    • 2017-05-12
    • 2010-11-19
    • 2013-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多