1

我的用户输入如下:

<form action="special.php" method="post">
    <input name="first1"> <input name="last1"> <input name="age1">
    <input name="first2"> <input name="last2"> <input name="age2">
    <input name="first3"> <input name="last3"> <input name="age3">
    <input name="first4"> <input name="last4"> <input name="age4">
    <input name="first5"> <input name="last5"> <input name="age5">
    <input name="first6"> <input name="last6"> <input name="age6">
    ...

    N
</form>

用户在表单中输入的数量由用户决定;意思是,用户可以在上面的代码中添加 5,10,20 行,创建合适的新输入元素(按照上面的模式)。

我的问题是,一旦表单被提交,迭代和打印所有 SET POST 变量的简单方法是什么?

就像是:

for($i=0; $i < $numPostVars; $i++){
   if(isset($_POST['first".$i."'])){
       //echo all first names post variables that are set
    }
}

// do the same from last names & age in separate loops
4

2 回答 2

4

我认为诀窍是将变量命名为略有不同,并利用 PHP 的特性将它们解压缩为数组。只需使用语法:first[1]. 然后在 PHP 中,您可以在 $_POST['first']['1'] 中找到它。然后,您可以使用迭代所有“第一个”输入

foreach($_POST['first'] as $first_input) {
  // ... 
}

还要记住,如果用户提交时该字段为空,浏览器可能不会发送该字段。

这是输入在 HTML 中的样子:

<input name="first[1]"> <input name="last[1]"> <input name="age[1]">

正如用户@DaveRandom 所指出的,还要考虑一个更分层的结构(想想你的数据库中的“行”):

<input name="people[1][first]"> <input name="people[1][last]"> <input name="people[1][age]">
于 2012-12-12T23:44:03.520 回答
2

输入可以被视为数组,其语法与 PHP 中使用的语法非常相似:

<input name="name[1]" value="value 1">
<input name="name[2]" value="value 2">

这将导致$_POST['name']如下所示:

array(
  1 => "value 1",
  2 => "value 2"
);

该原理可以扩展为包含多维和关联数组。因此,如果您要这样命名输入:

<input name="rows[1][first]"> <input name="rows[1][last]"> <input name="rows[1][age]">
<input name="rows[2][first]"> <input name="rows[2][last]"> <input name="rows[2][age]">

...您将能够轻松地$_POST['rows']使用foreach构造进行迭代。数据结构将非常类似于一组数据库结果。

foreach ($_POST['rows'] as $row) {
  // do stuff with $row['first'], $row['last'] and $row['age'] here
}

有几点需要注意:

  • 与 PHP 不同,HTML 中的关联数组键不需要引号,使用它们会产生您可能意想不到的结果。它会起作用,但不是你想象的那样。不过,您仍然需要在 PHP 中使用引号。
  • 据我所知,这种语法不是 W3C 标准。然而,PHP 总是按预期处理它。
于 2012-12-13T00:10:49.500 回答