如何在PHP中检索文本字段作为数组


How to retrieve text fields as an array in PHP

我有一个表单,如下所示,允许用户通过addmore按钮添加更多输入字段。我的问题是如何在POST中检索数组并将它们回显出来。如您所见,我有两个名称为product[]和quantity[]的输入字段(可以添加更多字段)。我必须使用一个foreach循环获得字段的值,并将其存储在一个变量$message中,以便在mail()中使用。我已经尝试了一个for each循环和我的for each循环代码如下

$product = $_POST['product'];
$quantity = $_POST['quantity'];
foreach($product as $value)
{
    $message = "<html><head>
        <title></title>
        </head>
        <body>
        <table> 
            <tr>
                <td>".$value."";
}
foreach($quantity as $value)
{
    $message.=" </td>
                <td>".$value."</td>
            </tr>
        </table>
        </body>
        </html>";
}

我的输入表单

 <form id="quick_post" method="post"> 
<table id="input_fields">
    <tr> 
        <td><input class="orderinput" type="text" name="product[]" /></td> 
        <td><input class="orderquan" type="text" name="quantity[]" size="1" maxlength="3" /></td>
    </tr>
 </tr>
</table>
<input class="more" type="button" value="Addmore" name="addmore" /> // a jquery script is processed on click to add more fields.       
<input class="send" type="submit" value="Send" name="send" /></form>

的输出是,我只打印第一行产品,剩下的行只打印或回显数量。如下图

Product Name  Quantity
aaaaaa       22 
             33 

问题是,在你的第一个foreach循环中,你只是覆盖了$message变量,最后一个产品名称被传递到第二个循环。

试试这个

echo "<html><head><title></title></head> <body> <table>";
for($i=0 ; $i < count($product) ; $i++) 
{
    echo "<tr><td>".$product[$i]."</td>";
    echo "<td>".$quantity[$i]."</td></tr>";
}
echo "</table></body></html>";

不确定,但在第一次foreach中,您可能需要将$message连接起来,就像您在第二次foreach中对$quantity所做的那样。

$product = $_POST['product'];

$quantity = $_POST['quantity'];

($ i = 0;美元我& lt;sizeof(产品);美元我+ +){

        $message.="<tr>
            <td>".$product[$i]."</td>
            <td>".$quantity[$i]."</td>
              </tr>";

}