我有一个在购物车中添加定制客串的功能。购物车存储在会话变量中。如果客户决定构建完全相同的客串,我不想向数组中添加另一个条目,我只希望能够在所述产品的数量上再添加1个条目。问题是,当脚本到达检查数组中是否存在这些值的时候,它会返回false,并向数组中添加一个新条目。我是php的新手,所以我不确定我的做法是否正确。
function AddToCart($subpid,$subtype,$subprice,$subtotal,$subcarving,$subline1,$subline2){
global $form;
$exist = false;
$i=0;
if(!isset($_SESSION['cart'])){
$_SESSION['cart'] = array(0 => array("Product ID" => $subpid, "Type" => $subtype, "Price" => "$".$subprice, "Subtotal" => "$".$subtotal, "Carving" => $subcarving, "Line 1" => $subline1, "Line 2" => $subline2, "Quantity" => 1));
}
else{
foreach($_SESSION['cart'] as $item){
$i++;
while(list($key,$value) = each($item)){
/* If product exist add 1 to quantity */
if($key == "Product ID" && $value == $subpid && $key == "Type" && $value == $subtype && $key == "Price" && $value == "$".$subprice && $key == "Subtotal" && $value == "$".$subtotal && $key == "Carving" && $value == $subcarving && $key == "Line 1" && $value == $subline1 && $key == "Line 2" && $value == $subline2){
array_splice($_SESSION['cart'], $i-1, 1, array(array("Product ID" => $subpid, "Type" => $subtype, "Price" => "$".$subprice, "Subtotal" => "$".$subtotal, "Carving" => $subcarving, "Line 1" => $subline1, "Line 2" => $subline2, "Quantity" => $item['Quantity'] + 1)));
$exist = true;
}
}
}
if($exist == false){
array_push($_SESSION['cart'], array("Product ID" => $subpid, "Type" => $subtype, "Price" => "$".$subprice, "Subtotal" => "$".$subtotal, "Carving" => $subcarving, "Line 1" => $subline1, "Line 2" => $subline2, "Quantity" => 1));
}
}
return 0;
}如果我只是使用:$key ==“产品ID”&& $value == $subid,它将返回true并更新数量,但问题是如果客户购买了两个具有相同id但不同雕刻的客串,或雕刻我的车将关闭。
发布于 2011-09-07 04:50:22
它不起作用,因为您使用&&语句同时比较每个键,但每次循环遍历每个键。去掉while循环,就像这样比较:
if( $item['Product ID'] == $subpid ... //etc ) {
}此外,您不需要array_splice,只需更新项目即可。
发布于 2011-09-07 04:51:01
我觉得你把事情搞得更复杂了……
我会这样设置购物车阵列:
$cart[0]["name"] = "whatever";
$cart[0]["ProductID"] = "1234";
$cart[0]["price"] = 0.00;
$cart[0]["quantity"] = 1;
$cart[0]["options"] = array(
"subcarving" => "asdf",
"subline1" => "asdfsafd",
"subline2" => "asfdsadfdf");然后你可以像这样用简单的循环来处理它:
$didadd = 0;
for($x = 0; $x < sizeof($cart); $x++) {
if($subid == $cart[$x]["ProductID"]) {
// check options
$sameOpts = 1;
foreach($cart[$x]["options"] as $key => $val) {
if($val != ${$key}) { // checks if the current items option[val] = function(val)
$sameOpts = 0;
}
}
if($sameOpts) {
$didadd = 1; // sets the flag that we added the element.
// increase quantity since the product id and options matched.
} else {
$didadd = 1;
// add new element
// sets the flag that we added the element
}
}
}
if(!$didadd) {
// still need to add the item
// do code to create new $cart item here.
}https://stackoverflow.com/questions/7325793
复制相似问题