繁体   English   中英

如果会话中已有产品,如何增加产品数量

[英]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; 
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM