首页 > 解决方案 > 如何使 ColdFusion 数组中的项目独一无二?

问题描述

我有一个正在将产品添加到结帐页面的购物车。如您所见,这是购物车结构的设置方式:

购物车转储的图片

问题是,我只希望出现唯一值,不重复。不知道如何使数组严格,所以它只包含唯一值。

标签: arrayscfml

解决方案


为了确保您的购物车对于每篇文章始终只有一个位置,我将使用结构而不是数组来让您的购物车中的每篇文章始终拥有一个位置,并避免使用同一篇文章的多个副本填充它。

通过为您的购物车使用结构,您可以创建一个结构键(例如,带有文章 ID),它也是对购物车中一篇唯一文章的唯一引用。如果您使用数组,则只有数字,您需要深入查看数据结构以验证商品是否已存在于购物车中。

这只是一个简单的例子,说明我如何使用数据结构。我没有添加诸如添加/删除单个文章单元之类的功能。这只是一个示例,看看我将如何处理购物车数据结构以使用唯一键对其进行引用,以便可以快速访问和进一步操作它。

<cfscript>

// function to add an article structure to the cart
function addArticleToCart(struct articleCartData required) {

    // If the article is not present in the cart, add it as a struct to the cart wirh it's own articleID as the cart struct key:
    If(!structKeyExists(cart, arguments.articleCartData.articleID)) {
        cart.append({
            "#arguments.articleCartData.articleID#": arguments.articleCartData
        });

    } else {
        // Add the quantity of the cart by one unit
        cart[arguments.articleCartData.articleID].quantity++
    };
};

//Define empty cart
cart = {};

//Define the article that will be added to the cart
articleToAdd = {
    articleID: "ART12345",
    articleName: "5650R Sheerweave Oyster",
    quantity: 1,
    unitPrice: 12.99
};

// Call the function to add the article to the cart
addArticleToCart(
    articleToAdd
);

writedump(cart);

addArticleToCart(
    articleToAdd
);

writedump(cart);

addArticleToCart(
    articleToAdd
);

writedump(cart);

</cfscript>

推荐阅读