-1

我刚刚开始学习如何创建购物车。

遇到了这个例子:

<?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”部分:

*$小计=$价格*$数量;$总计 += $小计;*

正如我所说,它确实有效;如果我在购物车中放置两件物品,例如:5 块(数量)每块 5 美元的岩石和 2 块每块 10 美元的鹅卵石,我会在相应的表格行中获得 25 美元的小部件和 20 美元的小计为小工具。我假设

*$SUBTOTAL = $price * $quantity* ----- 对此负责,对吗?

我不明白 TOTAL 是如何得出的(这是正确的——45 美元)。

代码的哪一部分将各个小计(即 25 美元和 20 美元)相加?

$total += $subtotal是如何工作的?

我想了解代码是如何工作/处理的,而不仅仅是因为它有效而接受它。

提前致谢。

4

2 回答 2

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;
}
于 2012-06-15T00:32:59.683 回答
0

运算符取表达式左侧的+=值,并将右侧的值相加。可以这样想:

$total = $total + $subtotal;

foreach()循环遍历所有项目,并在每次迭代中通过将产品的单价乘以其数量来计算该产品的 total.price,该数量临时存储在$subtotal.

于 2012-06-15T00:35:36.950 回答