Use php arrays and cookies to implement the shopping cart function
Source: Internet
Author: User
You can use php arrays and cookies to implement the shopping cart function by saving the cookie to the array to add, delete, and modify the array, each set of records in array is the information of a commodity (quantity, price, etc.). the shopping cart function is implemented using the php array and cookie. the method is to store the cookie into array, add, delete, and modify an array. each set of records in the array is the information of a commodity (quantity, price, etc)
The solution to shopping cart is to use cookies to record a two-dimensional array. One dimension represents every commodity. Two dimensions include the commodity id, the commodity quantity, and so on. they can be added by themselves. they are all two dimensions, and the attributes of each commodity you are willing to include will be added.
The following operations are generally performed on items in the shopping cart: add items, modify the quantity of items, delete items, and clear the shopping cart.
These operations are targeted at cookies. Each time, the array in the cookie is retrieved, added, modified, and deleted, and recorded in the cookie. To clear the shopping cart, you can simply set the cookie with the same name as null.
The code is as follows:
// Add to shopping cart
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 <> ""){
// Returns the maximum value of the array key name in reverse order.
$ Ar_keys = array_keys ($ cur_cart_array );
Rsort ($ ar_keys );
$ Max_array_keyid = $ ar_keys [0] + 1;
// Traverse the current shopping cart array
// Traverses the 0 value of each item information array. if the key value is 0 and the values are the same, the same item exists in the shopping cart.
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"
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.