2

当一个项目被添加到购物车时,项目 ID 和该项目的数量应该被显示。在这种情况下,仅从会话中解析数量。未显示项目 ID。此外,当添加不同的项目时,购物车应显示具有单独数量的第二个项目。

<?php 
session_start();


?>
<?php 
if (isset($_POST['pid'])) {
    $pid = $_POST['pid'];
    $wasFound = false;
    $i = 0;

    if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
        $_SESSION["cart_array"] = array(1 => array("item_id" => $pid, "quantity" => 1));
    } else {
        foreach ($_SESSION["cart_array"] as $each_item) {
            $i++;
            while (list($key, $value) = each($each_item)) {
                if ($key == "item_id" && $value == $pid) {
                array_splice($_SESSION["cart_array"], $i-1, 1,array(array("item_id" => $pid, "quantity" => $each_item['quantity'] + 1)));
                $wasFound = true;
               }
            }
        }
        if ($wasFound == false) {
        array_push($_SESSION["cart_array"], array("item_id" => $pid, "quantity" => 1));
    }
  }
 }
?>
<?php
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
    unset($_SESSION["cart_array"]);
}
?>
<?php
$cartOutput = "";
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>";
} else {
    $i = 0;
    foreach ($_SESSION["cart_array"] as $each_item) {
        $i++;
        $cartOutput .= "<h2>Cart item $i</h2>";
        while (list($key, $value) = each ($each_item)) {
            $cartOutput .= "key:$value<br />";
        }
    }
}
?>

有什么建议么?谢谢

4

1 回答 1

0

array_splice 中有一个错误:数组从 0 开始索引。是什么阻止您使用 foreach ($arr as $index=>$key) 语法?并且您至少在该示例中没有回显 $cartOutput 。

<?php 
session_start();

if (isset($_POST['pid'])) {
    $pid = intval($_POST['pid']);

    if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1){
        $_SESSION["cart_array"] = array(1 => array("item_id" => $pid, "quantity" => 1));
    } else {
        $found= false;
        foreach ($_SESSION["cart_array"] as $i => $each_item) {
            if ($each_item["item_id"] == $pid) {
                $_SESSION["cart_array"][$i]["quantity"] ++;
                $found = true;
            }
        }
        if (!$found)  {
                $_SESSION["cart_array"][] = array("item_id"=>$pid, "quantity"=>1);
        }
    }
 }
?>
<?php
if (isset($_GET['cmd']) && $_GET['cmd'] == "emptycart") {
    unset($_SESSION["cart_array"]);
}
?>
<?php
$cartOutput = "";
if (!isset($_SESSION["cart_array"]) || count($_SESSION["cart_array"]) < 1) {
    $cartOutput = "<h2 align='center'>Your shopping cart is empty</h2>";
} else {
    $i = 0;
    foreach ($_SESSION["cart_array"] as $each_item) {
        $i++;
        $cartOutput .= "<h2>Cart item $i</h2>";
        while (list($key, $value) = each ($each_item)) {
            $cartOutput .= "key:$value<br />";
        }
    }
}
echo $cartOutput;
?>
于 2013-03-16T20:16:16.893 回答