购物车的思路

2018-01-24  本文已影响0人  任人渐疏_Must

思路:
cookie只能存字符串,所以以1:2,2:1,3:2这种格式保存在cookie中,1:2 中 1:代表的是产品id product_id,2代表的是点击到购物车的次数$count。判断产品是否是第一次添加购物车,如果是第一次,添加新的产品,如果不是第一次,就在原有的基础上,找到指定的product_id 上的$count+1

 public function addCart(Request $request,$product_id){
       $bk_cart = $request->cookie('bk_cart');
       $bk_cart_arr = ($bk_cart != null ? explode(',',$bk_cart) : array());

       $count = 1;
       foreach($bk_cart_arr as &$value){
           $index = strpos($value,':');
           if(substr($value,0,$index) == $product_id){
               $count = ((int)substr($value,$index+1)) + 1;
               $value = $product_id .':'.$count;
               break;
           }
       }
       if($count == 1){
           array_push($bk_cart_arr,$product_id.':'.$count);
       }
       $m3_result = new M3Result();
       $m3_result->status=0;
       $m3_result->message = '添加成功';
       return response($m3_result->toJson())->withCookie('bk_cart',implode(',',$bk_cart_arr));
   }
上一篇 下一篇

猜你喜欢

热点阅读