PHP-购物车,会话问题
将项目添加到购物车时,应显示项目id和该项目的数量。在这种情况下,仅从会话中解析数量。未显示项目ID。此外,当添加不同的项目时,购物车应显示第二个单独数量的项目PHP-购物车,会话问题,php,Php,将项目添加到购物车时,应显示项目id和该项目的数量。在这种情况下,仅从会话中解析数量。未显示项目ID。此外,当添加不同的项目时,购物车应显示第二个单独数量的项目 <?php session_start(); ?> <?php if (isset($_POST['pid'])) { $pid = $_POST['pid']; $wasFound = false; $i = 0; if (!isset($_SESSION["cart_arr
<?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 />";
}
}
}
?>
这是一些非常奇怪的数组操作。您应该能够使用一个foreach
循环完成所有需要的操作:
foreach ($_SESSION["cart_array"] as $item_key => $each_item) {
if ( $each_item['item_id'] == $pid )
{
$_SESSION["cart_array"][$item_key]['quantity']++;
}
$wasFound = true;
}
如果您不熟悉,foreach($foo as$key=>$value)
是您编写的的正常方式,而(list($key,$value)=each($foo))
和$foo++
是$foo=$foo+1
的缩写
如果您使用产品ID作为购物车数组的键,实际上可以使这变得更简单;这样,您可以询问PHP是否存在密钥,如下所示:
if ( array_key_exists($pid, $_SESSION['cart_array']) )
{
$_SESSION['cart_array'][$pid]['quantity']++;
}
else
{
$_SESSION['cart_array'][$pid] = array('item_id' => $pid, 'quantity' => 1);
}