文章詳情頁
PHP新手中購物車實(shí)現(xiàn)的原理
瀏覽:4日期:2022-09-13 17:53:42
方法本質(zhì)是:把cookie存入array,對(duì)array進(jìn)行增加、刪除、修改操作,array中的每一組記錄都是一個(gè)商品的信息(個(gè)數(shù),價(jià)格等)解決購物車的思路是用cookie記錄一個(gè)二維數(shù)組。一維代表每一個(gè)商品,二維包含了商品的id,商品的數(shù)量...等可以自行增加,反正都是二維了,自己愿意帶多少個(gè)商品屬性就加上去。對(duì)購物車?yán)锷唐返牟僮饕话阌幸韵聨讉€(gè):添加商品,修改商品數(shù)量,刪除商品,清空購物車。這幾個(gè)操作都是針對(duì)cookie的。每次把cookie中的數(shù)組取出來,增加、修改、刪除一番,再記錄到cookie中。至于清空購物車,那就更簡(jiǎn)單了,直接設(shè)置同名的cookie為空就可以了。下面是我寫的具體操作函數(shù)//加入購物車function addcart($goods_id,$goods_num){ $cur_cart_array = unserialize(stripslashes($_COOKIE[’shop_cart_info’])); if($cur_cart_array==''){ $cart_info[0][] = $goods_id; $cart_info[0][] = $goods_num; setcookie('shop_cart_info',serialize($cart_info)); }elseif($cur_cart_array<>''){ //返回?cái)?shù)組鍵名倒序取最大 $ar_keys = array_keys($cur_cart_array); rsort($ar_keys); $max_array_keyid = $ar_keys[0]+1; //遍歷當(dāng)前的購物車數(shù)組 //遍歷每個(gè)商品信息數(shù)組的0值,如果鍵值為0且貨號(hào)相同則購物車存在相同貨品 foreach($cur_cart_array as $goods_current_cart){ foreach($goods_current_cart as $key=>$goods_current_id){ if($key == 0 and $goods_current_id == $goods_id){ echo '<script language=javascript>'; echo 'if(confirm(’購物車已經(jīng)有該商品,繼續(xù)購物按----確定!查看購物車按----取消!’))'; echo '{history.go(-1)}'; echo 'else{window.location.href=’http://blog.163.com/wz_pk007/blog/xqs_cart.php’}'; echo '</script>'; exit(); } } } $cur_cart_array[$max_array_keyid][] = $goods_id; $cur_cart_array[$max_array_keyid][] = $goods_num; setcookie('shop_cart_info',serialize($cur_cart_array)); } } //從購物車刪除function delcart($goods_array_id){ $cur_goods_array = unserialize(stripslashes($_COOKIE[’shop_cart_info’])); //刪除該商品在數(shù)組中的位置 unset($cur_goods_array[$goods_array_id]); setcookie('shop_cart_info',serialize($cur_goods_array)); } //修改購物車貨品數(shù)量function update_cart($up_id,$up_num,$goods_ids){ //先清空cookie,以便重新設(shè)置,傳遞過來三個(gè)數(shù)組參數(shù) 1數(shù)組的標(biāo)識(shí) 2商品數(shù)量數(shù)組 3商品編號(hào)數(shù)組 //如果不清空cookie則無法處理數(shù)量為零的商品 setcookie('shop_cart_info',''); foreach($up_id as $song){ //先返回?cái)?shù)組當(dāng)前單元;再把指針向下移動(dòng)一個(gè)位置 $goods_nums = current($up_num); $goods_id = current($goods_ids); next($up_num); next($goods_ids); //當(dāng)商品數(shù)量為空的時(shí)候,注銷此處的數(shù)組值并用continue 2 語句避開下面的操作,繼續(xù)做foreach循環(huán) while($goods_nums == 0){ unset($song); continue 2; } $cur_goods_array[$song][0] = $goods_id; $cur_goods_array[$song][1] = $goods_nums; } setcookie('shop_cart_info',serialize($cur_goods_array));
標(biāo)簽:
PHP
相關(guān)文章:
1. 三個(gè)不常見的 HTML5 實(shí)用新特性簡(jiǎn)介2. XML解析錯(cuò)誤:未組織好 的解決辦法3. IE6/IE7/IE8/IE9中tbody的innerHTML不能賦值的完美解決方案4. 存儲(chǔ)于xml中需要的HTML轉(zhuǎn)義代碼5. 告別AJAX實(shí)現(xiàn)無刷新提交表單6. 詳解CSS偽元素的妙用單標(biāo)簽之美7. ASP實(shí)現(xiàn)加法驗(yàn)證碼8. CSS3使用過度動(dòng)畫和緩動(dòng)效果案例講解9. XHTML 1.0:標(biāo)記新的開端10. 讀大數(shù)據(jù)量的XML文件的讀取問題
排行榜
