如果产品已存在于会话中,如何增加产品数量
How to increase product quantity if a product is already exist in session
我正在使用以下代码并想增加会话数组中的数量,但它不起作用
if(!empty($_SESSION['quote']))
{
$prdata=$_SESSION['quote'];
}
$product_id = $data['id'];
$product_image = $data['image'];
$product_name = $data['pname'];
$product_quantity = $data['quantity'];
$product_price = $data['price'];
foreach ($_SESSION["quote"] as $cart_itm){
if($cart_itm['product_id'] == $product_id){ //the item exist in array
$newdat = array('product_id' => $product_id,'quantity'=>$product_quantity,'price'=>$product_price,'name'=>$product_name,'image'=>$product_image);
$found = true;
}else{
$newdat = array('product_id' => $product_id,'quantity'=>$product_quantity,'price'=>$product_price,'name'=>$product_name,'image'=>$product_image);
}
你不需要再把product_id
等放在那里,只改变数量。您的代码将更短、更清晰,并且您可以避免其他可能的拼写错误等。
if($cart_itm['product_id'] == $product_id) {
$cart_itm['quantity'] += $product_quantity; // expect in $product_quantity is the amount you want to add to the current one
// it's a shorter variant of $cart_itm['quantity'] = $cart_itm['quantity'] + $product_quantity;
}
我正在使用以下代码并想增加会话数组中的数量,但它不起作用
if(!empty($_SESSION['quote']))
{
$prdata=$_SESSION['quote'];
}
$product_id = $data['id'];
$product_image = $data['image'];
$product_name = $data['pname'];
$product_quantity = $data['quantity'];
$product_price = $data['price'];
foreach ($_SESSION["quote"] as $cart_itm){
if($cart_itm['product_id'] == $product_id){ //the item exist in array
$newdat = array('product_id' => $product_id,'quantity'=>$product_quantity,'price'=>$product_price,'name'=>$product_name,'image'=>$product_image);
$found = true;
}else{
$newdat = array('product_id' => $product_id,'quantity'=>$product_quantity,'price'=>$product_price,'name'=>$product_name,'image'=>$product_image);
}
你不需要再把product_id
等放在那里,只改变数量。您的代码将更短、更清晰,并且您可以避免其他可能的拼写错误等。
if($cart_itm['product_id'] == $product_id) {
$cart_itm['quantity'] += $product_quantity; // expect in $product_quantity is the amount you want to add to the current one
// it's a shorter variant of $cart_itm['quantity'] = $cart_itm['quantity'] + $product_quantity;
}