如何用php从用户输入的select from中计算出总价?

问题描述 投票:0回答:1

我想计算用户输入的总价格,这些价格来自$_SESSION.然而,我的代码似乎有问题。

 <label>Seats STA:</label>
        <select name="seats[STA]" id="STA">
            <option value="0">0</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
            <option value="4">4</option>
            <option value="5">5</option>
            <option value="6">6</option>
            <option value="7">7</option>
            <option value="8">8</option>
            <option value="9">9</option>
            <option value="10">10</option>
        </select>
        <span class="error">* Please select atleast 1 seat <?php echo $seatErr ;?></span>

$_SESSION['seats']['STA']=$_POST['seats']['STA'];

$sta = 15;
$stp = 5;
$stc = 7.5;
$fca = 30;
$fcp = 20;
$fcc = 15;
$totalamount = "0.0";


$totalamount =  $_SESSION['seats']['STA'] * $sta +
                $_SESSION['seats']['STP'] * $stp +
                $_SESSION['seats']['STC'] * $stc +
                $_SESSION['seats']['FCA'] * $fca +
                $_SESSION['seats']['FCP'] * $fcp +
                $_SESSION['seats']['FCC'] * $fcc;

$tax = 0.1;

$totalprice = $totalamount * (1+$tax);                

number_format($totalprice,2);

我的问题是

  1. $sta 保存价格的正确方法?

  2. 如果不正确,我可以在哪里保存选择表格中的产品的价格?

  3. number_format($totalprice,2); 正确的方式来显示2个小数?

谢谢你阅读我的代码!

php session number-formatting price
1个回答
0
投票
  1. 你可以把你的价格保存在一个数组里. 例如,你也可以从JSON文件或数据库中读取。

  2. 价格不应该由用户发送。

  3. 如果你想显示价格是的,但如果你想继续计算价值。round($total_price, 2) 是比较合适的方法。

准则。

$_PRICES = array(
    "STA" => 15,
    "STP" => 5,
    "STC" => 7.5,
    "FCA" => 30,
    "FCP" => 20,
    "FCC" => 15
);

$total_price = 0;

foreach ($_SESSION['seats'] as $item => $amount) {
    $price = $_PRICES[$item];
    if ($price != null) {
        $total_price += $amount * $price;
    }
}

$tax = 0.1;

$total_price *= 1+$tax;

echo number_format($total_price,2);
© www.soinside.com 2019 - 2024. All rights reserved.