0

我正在制作购物车,但我被困在实际的购物车上。我在这里阅读了一些问题并尝试了它们,但它们要么对我不起作用,要么就是垃圾。

PHP 代码:addtocart.php

if(isset($_GET['product_id']) && isset($_GET['qty'])){
    $product_id = $_GET['product_id'];
    $qty = $_GET['qty'];
    $cart = $_SESSION['cart'];
    if($cart == null) {
        $cart = array();
    }
    if(!isset($cart[$product_id])) {
        $cart[$product_id] = 0;
    }
    $cart[$product_id] += $qty;
    //var_dump($cart);
}
$session->setSetting("cart", $cart);

PHP 代码:cart.php

try {
    if(empty($_GET)) {
        $cart = $session->getSetting("cart");
        if($cart == null) {
            throw new Exception("Empty cart.");
        } else {
            $template->setVar("cart", $cart);
        } elseif($_GET['action'] == 'empty') {
            unset($_SESSION['cart']);
            header("location: /cart.php");
        }
    }
} catch (Exception $e) {
    $template->setVar("errmsg", $e->getMessage());
}

输出:

<table class="table table-bordered table-striped table-condensed">
<?php foreach($this->cart as $product_id => $qty): 
$item = $this->product->buildTotal($product_id); //var_dump($item); 
?>

<tr>
    <th>Items</th>
    <td><?php echo count($item); ?>
</td>
<tr>
    <th>Sub-total</th>
    <td>
        &pound;<?php echo $price = number_format(($item[0]['product_price'] * $qty), 2); ?>
    </td>
</tr>
<tr>
    <th>Shipping</th>
    <td>
        &pound;<?php echo $shipping = "2.95"; ?>
    </td>
</tr>
<tr class="warning">
    <th>Tax</th>
    <td>20%</td>
</tr>
<tr class="success">
    <th>Total</th>
    <td>&pound;<?php $tax = (($price * 20) / 100);
        $total = ($price + $tax + $shipping); 
        echo number_format($total, 2); ?>
    </td>
</tr>
<?php endforeach; ?>

不幸的是,我的错误是购物车底部的总计表显示了“x”数量的产品的“x”次,两个产品的示例使表格显示两次,而不是仅仅合计不同的价格等。我已经坚持了三天,所以非常感谢任何帮助。此外,如果您的回答有效,我会在购物车的积分页面中列出您。

4

0 回答 0