我使用PHP制作了一个订单,为每个订购的商品制作小计。如何创建一个函数/代码来显示页面底部的订单总数。我试着在PHP.net上阅读,但无法弄明白。
以下是我的代码示例:
$bread = $_POST["bread"];
$cheese = $_POST["cheese"];
$eggs = $_POST["eggs"];
$priceBread = 5;
$priceCheese = 5;
$priceEggs = 3.6;
function subtotal($incomingQuantity, $incomingPrice){
return $incomingQuantity * $incomingPrice;
}
<div id="breadSubtotal">$<?php echo subtotal($bread, $priceBread); ?>
<div id="cheeseSubtotal">$<?php echo subtotal($cheese, $priceCheese); ?></div>
<div id="eggsSubtotal">$<?php echo subtotal($eggs, $priceEggs); ?></div>
我希望所有项目的小计中的总数
答案 0 :(得分:0)
这样的事情?
$total = 0;
function subtotal($incomingQuantity, $incomingPrice){
global $total;
$sub = $incomingQuantity * $incomingPrice;
$total += $sub;
return $sub;
}
然后在HTML
中<div id="total">$<?php echo $total; ?></div>
另外,不要忘记使用类似
之类的东西来保护你收到的$ _POST变量$bread = htmlspecialchars($_POST["bread"]);
答案 1 :(得分:0)
我希望所有项目的小计中的总数
计算起来非常简单。试试这个
$bread = 2;
$cheese = 3;
$eggs = 4;
$priceBread = 5;
$priceCheese = 5;
$priceEggs = 3.6;
$total = 0;
function subtotal($incomingQuantity, $incomingPrice){
return $incomingQuantity * $incomingPrice;
}
$total += subtotal($bread, $priceBread) ;
$total += subtotal($bread, $priceBread);
$total += subtotal($cheese, $priceCheese);
echo "order total : " + $total;
答案 2 :(得分:0)
如果没有错,您想要计算每件商品的数量和商品的价格。基于这一点,我就是这样做的。
public function getTotal()
{
$total = 0;
$subTotal = func_get_args();
for($a = 0; $a < sizeof($subTotal); $a++)
{
$total += $subTotal[$a];
}
return $total;
}
测试功能
getTotal(subtotal($bread, $priceBread), subtotal($cheese, $priceCheese), subtotal($eggs, $priceEggs));
答案 3 :(得分:0)
我就是这样做的,给你更多的灵活性
<?php
$bread = $_POST["bread"];
$cheese = $_POST["cheese"];
$eggs = $_POST["eggs"];
//prices
$prices = array('bread'=>5,'cheese'=>5,'eggs'=>3.6);
function calculateOrderTotals($items, $prices){
//result
$result = array('total'=>0, 'subTotal'=>array());
//total
$total = 0;
//calculate subtotal and total
foreach ($items as $item => $nPurchased){
$subTotal = $nPurchased* $prices[$item];
$result['subTotal'][$item] = $subTotal;
$total += $subTotal;
}
//set total
$result['total'] = $total;
//return
return $result;
}
//call function to calculate
$totals = calculateOrderTotals(array('bread'=>$bread,'cheese'=>$cheese,'eggs'=>$eggs), $prices);
?>
<div id="breadSubtotal"><?php echo $totals['subTotal']['bread'];?>
<div id="cheeseSubtotal"><?php echo $totals['subTotal']['cheese']; ?></div>
<div id="eggsSubtotal"><?php echo $totals['subTotal']['eggs']; ?></div>
<div id="total"><?php echo $totals['total']; ?></div>