购物车不响应空PHP


Shopping cart does not echo empty PHP

我的购物车从不为空,即使值为0。我错过了什么?请给我指正确的方向。我试图移动else语句,但这只会导致页面错误。

<?php
session_start();
include "cart.php";
include "style.php";

if (isset($_GET['add'])) {
    $_SESSION['id'.$_GET['add']]++;
}
if (isset($_GET['empty'])) {
    $_SESSION['id_'.$_GET['empty']]--;
    session_unset();
}
function cart() {
    echo "<h3>Shopping cart!</h3>";
    echo "<table>
    <tr>
    <td>Product</td>
    <td>Quantity</td>
    <td>Price</td>
    <td><a href='shoppingcart.php?empty=$name'>[Empty]</a></td>
    </tr>"; 
    foreach($_SESSION as $name => $value) {
    if ($value > 0) {
    echo "<table><tr><td>$name</td><td>$value</td></tr></table>";
}
    else {
    echo "Cart is empty";
}
}       
} 
?>

会话不是购物车,购物车也不是会话。cart本质上应该是一个包含数组的会话属性。

以下是基本想法(从您的代码开始):

<?php
session_start();
//create default empty cart
$cart = array();
if(isset($_SESSION['cart']))
{
   //get the cart from the session
   $cart = $_SESSION['cart'];
}
if (isset($_GET['add'])) 
{
   $cart[] = $_GET['add']; //add to cart array
}
if (isset($_GET['empty'])) 
{
    $cart = array(); //set cart array to empty array
}
//put the cart in the session
$_SESSION['cart'] = $cart;
function cart() 
{
?>
    <h3>Shopping cart!</h3>
    <table>
    <tr>
    <td>Product</td>
    <td>Quantity</td>
    <td>Price</td>
    <td><a href='shoppingcart.php?empty=true'>[Empty]</a></td>
    </tr>
<?php
    if(empty($cart))
    {
       echo "Cart is empty";
    }
    else
    {
       echo "<table>";
       foreach($cart as $name => $value) 
       {
            echo "<tr><td>$name</td><td>$value</td></tr>";
       }
       echo "</table>";
    }       
}