php - 是否可以从 HTML 表单(复选框)发布多个 "values"?

标签 php html arrays forms post

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

我已经通过“名称”属性为复选框建立了一个数组。

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

<?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>";

}
}
?>

有没有办法让我的 $key 变量实际上就像它设置的数组名称一样? 如果没有,有什么好的方法可以做到这一点?

最佳答案

因此在您的 HTML 表格中,您需要像这样呈现每个复选框:

<input type="checkbox" name="selectedIDs[]" value="$key" />

其中 $key 是项目编号。

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

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

$products = array( 1 => array("Big Red", 575), 2 => array("Spearmint", 525));

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

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>";
}

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

关于php - 是否可以从 HTML 表单(复选框)发布多个 "values"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10355330/

相关文章:

javascript - 每 2 秒重复一次 PHP 函数

php - Apache 用户无法连接到 smtp (Centos)

css - 在窗口调整大小时垂直移动 div block

html - 除非是纯文本,否则 SVG foreignObject 内容不会显示

arrays - 如何使用数组更改多个变量而不是值?

php - 使用 node-mysql 返回一个列(如 PDO 中的 fetchColumn)

php - $_COOKIE 如何检查它是否已设置?

html - 如果添加更多文本,标题会上升

c++ - 按字母顺序排列字符串数组(甚至 *ptr)

java - 如何清空特定的字符数组位置