国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

Table of Contents
Reply content:
Home Backend Development PHP Tutorial javascript - Please help with the problem of implementing shopping cart array! ! ! ! ! !

javascript - Please help with the problem of implementing shopping cart array! ! ! ! ! !

Jul 06, 2016 pm 01:53 PM
css html html5 javascript php

Each product has an id, title, and price. Every time I click to buy, I add it to the array. However, I want to judge based on the Id. When adding a product to the shopping cart repeatedly, add the same product to an array. How to write a dimensional array?

<code>[
    [
        {雞腿},{雞腿},{雞腿},{雞腿}
    ],
    [
        {狗腿},{狗腿},{狗腿}
    ],
    [
        {貓咪},{貓咪},{貓咪},{貓咪},{貓咪},{貓咪}
    ]
]




</code>

Thank you everyone, it’s true that my idea is really stupid, thank you for your suggestions!

Reply content:

Each product has an id, title, and price. Every time I click to buy, I add it to the array. However, I want to judge based on the Id. When adding a product to the shopping cart repeatedly, add the same product to an array. How to write a dimensional array?

<code>[
    [
        {雞腿},{雞腿},{雞腿},{雞腿}
    ],
    [
        {狗腿},{狗腿},{狗腿}
    ],
    [
        {貓咪},{貓咪},{貓咪},{貓咪},{貓咪},{貓咪}
    ]
]




</code>

Thank you everyone, it’s true that my idea is really stupid, thank you for your suggestions!

The friend above is right, your idea is not advisable. Two-dimensional arrays are all the same thing. . A bit of a trap.
This format is better, please refer to it

<code>var cart = {
    'id01':{n:'雞腿', count: 4},
    'id02':{n:'鴨腿', count: 3},
    'id03':{n:'豬腿', count: 2},
    'id04':{n:'狗腿子', count: 1}
}
</code>

However, if you insist on doing it this way

<code>var list = [
    [{n:'雞腿'},{n:'雞腿'},{n:'雞腿'},{n:'雞腿'},{n:'雞腿'}],
    [{n:'鴨腿'},{n:'鴨腿'},{n:'鴨腿'},{n:'鴨腿'}],
    [{n:'豬腿'},{n:'豬腿'},{n:'豬腿'},{n:'豬腿'}]
];

function fn(o){
    var inArray = false;
    list.map(function(item){
        if( item.indexOf(o) > -1){
            inArray = true;
            item.push(o);
        }
    });
    inArray || list.push([o]);
}

fn(list[1][1]);

fn({n:'狗腿子'});
</code>

This is just a reference and is not recommended

It is not recommended to write like this. The data structure of the shopping cart should store the product ID and quantity (assuming that the product ID here is the name)

<code>{
    "雞腿": 4,
    "狗腿": 3,
    "貓咪": 6
}
</code>

In actual implementation, when adding or subtracting items in the shopping cart, you only need to add or subtract the following number

Your thinking is wrong. What you said above is correct. The main body of the shopping cart should be $a = ['id'=>number], then the price and name should be another array $b = ['id'=>['name'=>name,'price'=>price]], and the total price is $totalPrice = $a['id']*$b['id']['price']

I agree with the point above that the items in the shopping cart should be as a whole, but I personally feel that the price should not be stored in the shopping cart array, because the price when you add it and the price when you pay are not necessarily the same. What should be stored is the unique identifier id and quantity number. If you store title, price, if the merchant changes the name or price, how should your design be handled?

<code>$shoppingCart = [
    '101' => 4,//雞腿
    '102' => 5,//狗腿
    '103' => 6//鴨腿
];</code>

First of all, thank you for the invitation.

Actually, I saw this question yesterday, and I think the answers above were pretty good. But seeing that the author of the question invited me again, I can only express my opinion as a way to attract others.


Actually, I think the number of dimensions of the array is not important. It is not important how to write it. What is important is the idea. I mainly want to make an introductory statement on this aspect.
In fact, in this day and age, although object-oriented is a commonplace thing, many people still don’t know how to use it, so the complexity of the problem has skyrocketed. Let’s try to use object-oriented to solve this problem:

//全局對(duì)象
var item_arr = {};

//操作函數(shù)
function add_(id, name, price, count) {
    var item = {
        id: id,
        name: name,
        price: price,
        count: count
    }
    var obj = item_arr[id]
    if (obj) {
        item.count = obj.count + count;
    }
    item_arr[item.id] = item;
}
//code by rozbo ,強(qiáng)力免山寨


//模擬添加購(gòu)物操作
add_(19, "狗腿子", 16, 20);
add_(1, "雞腿子", 12, 2);
add_(126, "羊腿子", 6, 6);
add_(126, "羊腿子", 6, 6);


//輸出信息,計(jì)算價(jià)格
var price_totle = 0;
for (var id in item_arr) {
    var item = item_arr[id];
    var price_curr = item.count * item.price;
    price_totle += price_curr;
    console.info("當(dāng)前有%s%d個(gè),總價(jià)%d元", item.name, item.count, price_curr);
}
console.info("共計(jì)%d元,祝您購(gòu)物愉快!", price_totle);

Output results
javascript - Please help with the problem of implementing shopping cart array! ! ! ! ! !

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use php exit function? How to use php exit function? Jul 03, 2025 am 02:15 AM

exit() is a function in PHP that is used to terminate script execution immediately. Common uses include: 1. Terminate the script in advance when an exception is detected, such as the file does not exist or verification fails; 2. Output intermediate results during debugging and stop execution; 3. Call exit() after redirecting in conjunction with header() to prevent subsequent code execution; In addition, exit() can accept string parameters as output content or integers as status code, and its alias is die().

How to combine two php arrays unique values? How to combine two php arrays unique values? Jul 02, 2025 pm 05:18 PM

To merge two PHP arrays and keep unique values, there are two main methods. 1. For index arrays or only deduplication, use array_merge and array_unique combinations: first merge array_merge($array1,$array2) and then use array_unique() to deduplicate them to finally get a new array containing all unique values; 2. For associative arrays and want to retain key-value pairs in the first array, use the operator: $result=$array1 $array2, which will ensure that the keys in the first array will not be overwritten by the second array. These two methods are applicable to different scenarios, depending on whether the key name is retained or only the focus is on

Applying Semantic Structure with article, section, and aside in HTML Applying Semantic Structure with article, section, and aside in HTML Jul 05, 2025 am 02:03 AM

The rational use of semantic tags in HTML can improve page structure clarity, accessibility and SEO effects. 1. Used for independent content blocks, such as blog posts or comments, it must be self-contained; 2. Used for classification related content, usually including titles, and is suitable for different modules of the page; 3. Used for auxiliary information related to the main content but not core, such as sidebar recommendations or author profiles. In actual development, labels should be combined and other, avoid excessive nesting, keep the structure simple, and verify the rationality of the structure through developer tools.

php raw post data php php raw post data php Jul 02, 2025 pm 04:51 PM

The way to process raw POST data in PHP is to use $rawData=file_get_contents('php://input'), which is suitable for receiving JSON, XML, or other custom format data. 1.php://input is a read-only stream, which is only valid in POST requests; 2. Common problems include server configuration or middleware reading input streams, which makes it impossible to obtain data; 3. Application scenarios include receiving front-end fetch requests, third-party service callbacks, and building RESTfulAPIs; 4. The difference from $_POST is that $_POST automatically parses standard form data, while the original data is suitable for non-standard formats and allows manual parsing; 5. Ordinary HTM

How to create an array in php? How to create an array in php? Jul 02, 2025 pm 05:01 PM

There are two ways to create an array in PHP: use the array() function or use brackets []. 1. Using the array() function is a traditional way, with good compatibility. Define index arrays such as $fruits=array("apple","banana","orange"), and associative arrays such as $user=array("name"=>"John","age"=>25); 2. Using [] is a simpler way to support since PHP5.4, such as $color

Declaring the correct HTML5 doctype for modern pages. Declaring the correct HTML5 doctype for modern pages. Jul 03, 2025 am 02:35 AM

Doctype is a statement that tells the browser which HTML standard to use to parse the page. Modern web pages only need to be written at the beginning of the HTML file. Its function is to ensure that the browser renders the page in standard mode rather than weird mode, and must be located on the first line, with no spaces or comments in front of it; there is only one correct way to write it, and it is not recommended to use old versions or other variants; other such as charset, viewport, etc. should be placed in part.

What are the essential HTML elements for structuring a webpage? What are the essential HTML elements for structuring a webpage? Jul 03, 2025 am 02:34 AM

The web page structure needs to be supported by core HTML elements. 1. The overall structure of the page is composed of , , which is the root element, which stores meta information and displays the content; 2. The content organization relies on title (-), paragraph () and block tags (such as ,) to improve organizational structure and SEO; 3. Navigation is implemented through and implemented, commonly used organizations are linked and supplemented with aria-current attribute to enhance accessibility; 4. Form interaction involves , , and , to ensure the complete user input and submission functions. Proper use of these elements can improve page clarity, maintenance and search engine optimization.

Handling reconnections and errors with HTML5 Server-Sent Events. Handling reconnections and errors with HTML5 Server-Sent Events. Jul 03, 2025 am 02:28 AM

When using HTML5SSE, the methods to deal with reconnection and errors include: 1. Understand the default reconnection mechanism. EventSource retrys 3 seconds after the connection is interrupted by default. You can customize the interval through the retry field; 2. Listen to the error event to deal with connection failure or parsing errors, distinguish error types and execute corresponding logic, such as network problems relying on automatic reconnection, server errors manually delay reconnection, and authentication failure refresh token; 3. Actively control the reconnection logic, such as manually closing and rebuilding the connection, setting the maximum number of retry times, combining navigator.onLine to judge network status to optimize the retry strategy. These measures can improve application stability and user experience.

See all articles