如何从使用foreach循环创建的表单中检索_POST数据?

时间:2019-02-08 18:05:51

标签: php post foreach

我有一个20个名称的关联数组,格式如下:

$operationCodeName = array(
    "Overlord" => 44,
    "Rolling Thunder" => 68,
    "Desert Storm" => 91,
    "Phantom Fury" => 04,
...);

...并使用以下foreach循环生成一个表格(嵌套在表格中),该表格显示每个名称和一个整数年份:

foreach($operationCodeName as $operation => $year) {
    echo "<tr>
          <td>" . $operation . "</td>
          <td align='center'>" . $year . "</td>";
    echo "<td><input name='comment" . $operation . "' size='50' type='text' placeholder='Comment here'></td>
    </tr>";
    }

我通过在文本输入的name属性中将单词'comment'与$operation变量连接来命名变量。

这部分工作正常,尽管如果有更聪明的方法可以做到这一点,那么我真是耳目一新!

当用户单击“提交”按钮时,我需要将这些评论显示在摘要页面上。该表应显示与第一页相同的$operation$year数组元素,但随后显示前一页的用户注释。

我尝试使用分为两部分的解决方案来解决该问题:

首先,我的想法是使用先前的关联数组创建每个串联变量,并使用它调用_POST方法:

foreach($operationCodeName as $key => $value){
    ${"comment" . $key} = $_POST[${"comment" . $key}];
}

...然后,通过回显串联的变量,在注释列中逐个循环,就像我在第三列的上一页中设置它们一样:

foreach($operationCodeName as $operation => $year) {
        echo "<tr>
                <td>" . $operation . "</td>
                <td align='center'>" . $year . "</td>";
        echo "<td>" . ${"comment" . $operation} . "</td>
            </tr>";
    }

运行此代码时,该表正确显示前两列,但为第三列生成空的<td></td>标记。 var_dump(_$POST);显示:

array(21) { ["commentOverlord"]=> string(9) "Comment 1" ...

“注释1”是在上一页中输入的注释,因此数据在此处,我只是没有正确地调用它以使其显示在表中……这实际上令人鼓舞!

我假设我没有正确地声明变量,但是我不确定在哪里发生误解。

如何正确地从第一页检索注释,并将其显示在此动态生成的表的第三列中?

感谢您提出的所有建议!虽然我已经用Java编程了大约一年,但是我只使用PHP大约2周。就是说,请您原谅我的新秀错误!

1 个答案:

答案 0 :(得分:2)

在上面的代码中,您尝试为每个注释创建动态变量。这不是动态变量的创建方式。您已经以数组形式在POST请求中获得了数据,因此您可以通过在表单注释中创建的键(与operationCode号连接)访问每个注释。试试吧!

foreach($operationCodeName as $operation => $year) {
        // replace space in operation key with _
        $operation = preg_replace('/\s+/', '_', $operation);
        $commentKey = "comment" . $operation;
        $comment = $_POST[$commentKey];
        echo "<tr>
                <td>" . $operation . "</td>
                <td align='center'>" . $year . "</td>";
        echo "<td>" . $comment . "</td>
            </tr>";
}