从多维数组中的 HTML 中获取值并使用 PHP 计算值


Get values from HTML in a multidimensional array and calculate values using PHP

我已经搜索过,但无法解决这个问题。

我正在开发一个应用程序,该应用程序将生成未知数量的项目,并让用户从每个项目的下拉列表中选择数量。例如。

Item(s) | price | Select qty
Rice     23      3
Beans    22      4
Eggs     52      5
...
...
...
unknown

请问,如何在数组中捕获上述内容并计算所有选定项目的总价值和相应的费用?

我有以下 HTML 代码:

<form id='form1' name='form1' method='post' action='item_calc.php'>
<?php
    .....
while($t_row = mysql_fetch_assoc($get_items)) {
echo "<p><label>$t_row['$item_name']
<input type='text' READONLY name='item_price[]' value='$t_row['$item_price']' /></label>
<input type='text' READONLY name='item_fees[]' value='$t_row['$item_fee']' /> 
<select name="item_qty">
<option value="1">
<option value="2">
<option value="3">
<option value="4">
<option value="5">
</select>
</p><p>";
}
        echo "<label><input type='submit' name='submit'  value='Submit' /></label></p>
         </form>";

请问,我怎样才能获得所有选定项目的item_price[] + item_fees[] * item_qty?

这是我尝试过的:

for ($i = 0; $i < count($_POST['item_price']); $i++) {
   // Do something here with $_POST['checkbx'][$i]

   foreach ($_POST['item_fees'] as $tkey => $tvalue) {
    //echo "Key: $tkey; Value: $tvalue<br>";
   }

   foreach ($_POST['item_price'] as $pkey => $pvalue) {
    //echo "Key: $pkey; Value: $pvalue<br>";
   }
   $total = $tvalue + $pvalue;

}
echo $total;

我建议不要将费用和价格放入表格中,并从 POST 请求中读出。有些人会做一些不好的事情,比如html注入或后参数操作。您让他们能够使用操纵的 POST 参数向您发送带有自己的价格和费用的请求。

最简单的方法是使用 Firefox 打开您的页面并使用 firebug 操纵 price[] 和 fee[] 的值,然后按提交 - 即使输入是只读的!!

我的提示 - 做这样的事情:

<select name="quantity[unique-id]">
  <option value="null">choose...</option>
  ...your options...
</select>
其中唯一 ID

是每个产品的唯一标识符,如数据库 ID。

然后在 php 中

foreach ($_POST['quantity'] as $uniqueId => $quantity) {
  //... don't forget to check $uniqueId and $quantity for injections (like sql injections)
  //skip the products with no numeric quantity value
  if (!is_int($quantity) || $quantity < 1) {
    continue;
  }
  $fee = getFeeFor($uniqueId); // from database?
  $price = getPriceFor($uniqueId); // from database?
  //... do what you want: $price + $fee * $quantity
}

我希望这对你有帮助。

  1. 首先,不要在双引号字符串中包含单引号当您引用数组时,您可能会有一个"封装的字符串"错误。
  2. 您还可以在"item_qty"中包含双引号字符串,这将可能会导致错误。
  3. 最佳做法是使用 /> 关闭 option 标记。
  4. 您的LABEL标签未正确使用。正确的语法是:<label for='html_element_id'>My pretty label</label> <input id='html_element_id ... (my form control) ... />,它对复选框或单选按钮以外的其他控件非常有用(尽管总是更具语义和结构化)。
  5. 您可以使用 TABLE 而不是 P 标签来拥有一切都排好了。更好的是,你可以使用CSS来排列东西,更好的做法。
  6. 如果对选择进行硬编码,则可能难以处理需求更改:如果您需要从 1 到 10 的数量怎么办?如果选择使用文本框而不是SELECT怎么办?

    while($t_row = mysql_fetch_assoc($get_items)) 
    {
        // Generate quantity string - can change the $qty string
        // for any imput method you like
        $qtyName = "item_qty[]";
        $qty = "<select name='" . $qtyName . "'>";
        for ($i=1; $i<6; $i++)
        {
            // close the option tag as best practice!
            $qty .= "<option value='" . $i . "' />";
        }
        $qty .= "</select>";
        echo sprintf("<p>%s
        <input type='text' READONLY name='item_price[]' value='%s' /></label>
        <input type='text' READONLY name='item_fees[]' value='$s' /> " . $qty . "</p>",
        $t_row['item_price'],
        $t_tow['item_fee']);
    }
    

收集数据很简单:

$sum = 0;
$fees = $_POST['item_fee'];
$qtys = $_POST['item_qty'];
$prices = $_POST['item_price'];
$total = count($prices);
for ($i = 0; $i<total; $i++)
{
    $item_fee = $fees[$i] + 0; // trick to filter only numerical values and avoid data tampering
    $item_price = $price[$i] + 0;
    $item_quantity = $qtys[$i] + 0;
    $item_total = $item_price + $item_fee * $item_quantity; 
    $sum += $item_total;
}

我也同意,在您的表格中直接表示价格无论如何都会导致数据篡改,建议您检查数据库的用户给出了非常明智的建议。

$total = 0;
$fee = $_POST['item_fee'];
$qty = $_POST['item_qty'];
foreach($_POST['item_price'] as $k => $price) {
    $total += $price + ($fee[$k] * $qty[$k];
}

不确定您是想要所有 iten 的总计,还是每个项目的总计。

如果要对每个项目进行总计,请将$total += $price + ($fee[$k] * $qty[$k];更改为$total = $price + ($fee[$k] * $qty[$k];并删除第一行 ( $total = 0; )。

<select name="item_qty">更改为<select name="item_qty[]">

我有一个非常简单的解决方案。

第一次将<select name="item_qty">更改为<select name="item_qty[]">

然后在你的item_calc.php,写这个

$itemprice = $_POST["item_price"];//tested with array(10,35,21)
$itemfees = $_POST["item_fees"];//tested with array(3,7,4)
$itemqty = $_POST["item_qty"];//tested with array(2,5,3)
$i = 0;
$total = 0;
foreach($itemprice as $price){
  $feesx = $itemfees[$i];
  $qtyx = $itemqty[$i];
  $calculated = ($price+$feesx)*$qtyx;
  $total = $total + $calculated;
  $i++;
}
echo $total;//echos 311 [{(10+3)*2}+{(37+7)*5}+{(21+4)*3}]

我测试了它并且工作得很好。希望这对:)有所帮助