【发布时间】:2016-09-08 06:23:43
【问题描述】:
我目前正在大学学习 PHP。我正在尝试创建一个功能来检查一个项目是否已经在购物车会话中。如果是,则将数量增加 1,如果不是,则将其添加到购物车数组中。
添加新项目似乎可以正常工作,并且在添加多个相同项目时该功能可以正常工作,但是,当我向数组中添加另一个项目时,问题就出在了。它添加了新项目,但是如果我尝试放置另一个相同的项目,它会将另一个项目添加到数组中,而不是将数量增加 1。
似乎 for 循环无法按我的意愿工作。任何建议将不胜感激!
function addItemToCart($mysqli) {
$itemID = (int)$_GET['add'];
$counterItemsInCart = 0;
$alreadyInCart = false;
if(is_int($itemID)) { //makes sure the ID is passed as an int
$query = "SELECT product_id, product_name, product_price FROM product WHERE product_id = ?";
$stmt = $mysqli->prepare($query);
$stmt->bind_param("i", $itemID); // bind variables
$stmt->execute();
$result = $stmt->get_result();
if($rows = $result->fetch_assoc())
{
//setts all info needed to variables.
$pID = $rows['product_id'];
$pName = $rows['product_name'];
$pPrice = $rows['product_price'];
}
else
{
//if the item id is not an int display this message...
echo "not working";
}
if(isset($_SESSION['cart'])) { //check if any item in cart already
$intArraySize = count($_SESSION['cart']);
//loop through cart array
for($i = 0; $i < $intArraySize; $i+=1)
{
//check if item already exists in cart.
if($_SESSION['cart'][$i]["item_id"] === $pID)
{
$_SESSION['cart'][$i]["item_quantity"] += 1;
$alreadyInCart = true;
echo "<script type='text/javascript'>alert('item in cart');</script>";
}
}//loop to cycle through items in array...
if($alreadyInCart === false) { echo "<script type='text/javascript'>alert('item not in cart');</script>";
array_push($_SESSION['cart'], array($intArraySize =>array("item_id" => $pID, "item_name" => $pName, "item_price" => $pPrice, "item_quantity" => 1)));
}//close if statement check if same item is in array, if not add it.
}//close if statement checking if any item at all in shopping cart.
else {echo "<script type='text/javascript'>alert('new item');</script>";
$_SESSION['cart'] = array(array("item_id" => $pID, "item_name" => $pName, "item_price" => $pPrice, "item_quantity" => 1));
}
}//ends if statement checking if the id of the item is a int or string.
}//ends function
var_dump 输出
array(3) { [0]=> array(4) { ["item_id"]=> int(1) ["item_name"]=> string(10) "粉色衬衫" ["item_price"]= > string(4) "9.99" ["item_quantity"]=> int(3) } [1]=> array(1) { [1]=> array(4) { ["item_id"]=> int(2 ) ["item_name"]=> string(14) "绿色 w/Button" ["item_price"]=> string(5) "14.99" ["item_quantity"]=> int(1) } } [2]=>数组(1) { [2]=> 数组(4) { ["item_id"]=> int(2) ["item_name"]=> string(14) "Green w/Button" ["item_price"]=> string(5) "14.99" ["item_quantity"]=> int(1) } } }
这是一件接一件地添加三件粉红色的衬衫,然后是两件绿色的衬衫。出于某种原因,绿色的被视为不同的项目。
对不起,如果格式不好,不确定我应该如何格式化 var_dump 现在会检查这个...
【问题讨论】:
-
请 var_dump
$_SESSION['cart']以便我们看到结构? -
添加了 $_SESSION['cart'] 的 var_dump
-
访问这个数组似乎一切正常...尝试在 if 语句之前回显
$_SESSION['cart'][$i]["item_id"]和$pID的值,也许它会给你一个线索?