我刚开始学习如何制作购物车。
遇到这个例子:
<?php
echo "Shopping cart:\n";
$items = count($_SESSION['cart']);
{
$total = 0;
echo "<table width=\"100%\" cellpadding=\"1\" border=\"1\">\n";
echo "<tr><td>Item Name</td><td>Quantity</td><td>Total</td></tr>\n";
foreach($_SESSION['cart'] as $itemid => $quantity)
{
$query = "SELECT description, price FROM items WHERE itemid = $itemid";
$result = mysql_query($query);
$row = mysql_fetch_array($result, MYSQL_ASSOC);
$name = $row['name'];
$price = $row['price'];
$subtotal = $price * $quantity;
$total += $subtotal;
printf("<tr><td>%s</td><td>%s</td><td>$%.2f</td></tr>\n", $name, $quantity, $subtotal);
}
printf("<tr><td colspan=\"2\">Total</td><td>$%.2f</td></tr>\n", $total);
echo "</table>\n";
}
?>
代码有效,除了“TOTAL或$ total”部分之外,我理解其中的大部分内容:
* $ subtotal = $ price * $ quantity; $ total + = $ subtotal; *
正如我所说,它确实有效;如果我在购物车中放置两件物品,例如:每件5美元的5件(数量)岩石和每件10美元的2件鹅卵石,我会在每件25美元的表格行上获得SUBTOTALS $ 20对于小工具。我假设
<$> * $ SUBTOTAL = $ price * $ quantity * -----对此负责,对吗?我没有得到的是如何提出TOTAL(这是正确的 - 45美元)。
代码的哪一部分加起来是单个小计(即$ 25和$ 20)?
$ total + = $ subtotal 如何工作?
我想了解代码是如何工作/处理的,而不仅仅是因为它起作用。
提前致谢。
答案 0 :(得分:1)
$total += $subtotal
只是简写:
$total = $total + $subtotal;
所以将它应用于代码:
// Start the total at 0
$total = 0;
// For every item in the cart
foreach($_SESSION['cart'] as $itemid => $quantity)
{
// Get the item's price from the database
$price = $row['price'];
// The subtotal is the cost of each item multiplied by how many you're ordering
$subtotal = $price * $quantity;
// Add this subtotal to the running total
$total += $subtotal;
}
答案 1 :(得分:0)
+=
运算符取表达式左侧的值,并添加右侧的任何内容。可以这样想:
$total = $total + $subtotal;
foreach()
循环遍历所有项目,并在每次迭代中通过将产品的单位价格乘以其临时存储在$subtotal
中的数量来计算该产品的total.price。