是否可以从HTML表单(复选框)中发布多个"值"?

Est*_*ten 2 html php forms arrays post

我正在为PHP开发一些产品的订购页面.用户需要能够选择多种类型的产品,因此HTML表单中需要使用复选框.

我已经通过"name"属性为复选框建立了一个数组.

我的问题是,我想显示用户在确认页面上选择的内容,因此我希望这些复选框的"价值"最终返回产品名称和产品价格.据我所知,我只会被一个值所困,所以我试图解决这个问题:

<?php
//variables for the array and the count
$parray = $_POST['product'];
$pcount = count($parray);

//arrays for each product's information; i've only listed one for simplicity
$br = array("Big Red", 575);

/*The idea for this was for each product ordered to add a line giving the product information and display it. When the $key variable is assigned, it is stored simply as a string, and not an array (yielding [0] as the first letter of the string and [1] as the second), which I expected, but my general idea is to somehow use $key to reference the above product information array, so that it can be displayed here*/


if (!empty($parray))
{
    for ($i=0; $i < $pcount; $i++)
{
    $key = $parray[i];
    echo "<tr><td height='40'></td><td>" . $key[0] . "</td><td>" . $key[1] . "</td></tr>";

}
}
?>
Run Code Online (Sandbox Code Playgroud)

反正有没有让我的$ key变量实际上就好像它被设置为数组的名称一样?如果没有,有什么好办法吗?

Uch*_*uku 6

因此,在HTML表格中,您需要渲染每个复选框,如下所示:

<input type="checkbox" name="selectedIDs[]" value="$key" />
Run Code Online (Sandbox Code Playgroud)

$key物品编号在哪里.

然后,在PHP中,您将拥有一个$_POST["selectedIDs"]变量,该变量是已检查的所有项目编号的数组.

假设你有一个像这样的产品列表数组:

$products = array( 1 => array("Big Red", 575), 2 => array("Spearmint", 525));
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用如下循环打印所选产品的列表:

for($i = 0; $i < count($_POST["selectedIDs"]); $i++) {
    $key = $_POST["selectedIDs"][$i];
    $product = $products[$key];
    echo "<tr><td height='40'></td><td>" . $product[0] . "</td><td>" . $product[1] . "</td></tr>";
}
Run Code Online (Sandbox Code Playgroud)

这和你写的内容之间唯一真正的区别是我的$products数组是二维的,我$key用来从$products数组中获取相关的产品.