这只是我得到的结果的图片。如您所见,可以反复添加第4项。我在购物车中想要的是,对于每种颜色,第4项只能添加一次。
if( isset($_SESSION['cart']) ){
################## Do looping to check array cart if already has item with same id and color ##########################
$i = 0;
$j = 1; // set to index [1] //
$found = '';
foreach( $_SESSION['cart'] as $cart ){
######## Check if product chosen already exist in the cart #######
if( $cart[$i]['id'] == $new_product['id'] && $cart[$i]['color'] == $new_product['color'] ){
$found = true; // Found existing item in the array cart //
}
else{
$found = false;
$j++; // No item found in array cart, increase to index [2] //
}
####### If no same item is found in cart, add the new product to the cart array ###############
$i++; // Increase array index to check second array and so on //
}
if(!$found){ // No item found in array cart, add item into cart //
$_SESSION['cart'][$j]['id'] = $new_product['id'];
$_SESSION['cart'][$j]['product_name'] = $new_product['product_name'];
$_SESSION['cart'][$j]['discount'] = $new_product['discount'];
$_SESSION['cart'][$j]['qty'] = $new_product['qty'];
$_SESSION['cart'][$j]['color'] = $new_product['color'];
$_SESSION['cart'][$j]['shipping_fee'] = $new_product['shipping_fee'];
}
}
else{
$_SESSION['cart'][0]['id'] = $product['id'];
$_SESSION['cart'][0]['product_name'] = $product['product_name'];
$_SESSION['cart'][0]['discount'] = $product['discount'];
$_SESSION['cart'][0]['qty'] = $qty;
$_SESSION['cart'][0]['color'] = $color;
$_SESSION['cart'][0]['shipping_fee'] = $shipping_fee;
}
我怎样才能更改我的代码?
答案 0 :(得分:0)
试试这个......
if($found){ // item found in array cart
$_SESSION['cart'][0]['id'] = $product['id'];
$_SESSION['cart'][0]['product_name'] = $product['product_name'];
$_SESSION['cart'][0]['discount'] = $product['discount'];
$_SESSION['cart'][0]['qty'] = $qty;
$_SESSION['cart'][0]['color'] = $color;
$_SESSION['cart'][0]['shipping_fee'] = $shipping_fee;
}
}
else{ // no item found
$_SESSION['cart'][$j]['id'] = $new_product['id'];
$_SESSION['cart'][$j]['product_name'] = $new_product['product_name'];
$_SESSION['cart'][$j]['discount'] = $new_product['discount'];
$_SESSION['cart'][$j]['qty'] = $new_product['qty'];
$_SESSION['cart'][$j]['color'] = $new_product['color'];
$_SESSION['cart'][$j]['shipping_fee'] = $new_product['shipping_fee'];
}