简体   繁体   English

PHP-数组唯一和计数元素

[英]PHP - Array Unique and count elements

I am developing a shopping cart and come across a problem with regards to unique purchases. 我正在开发一个购物车,并且遇到有关唯一购买的问题。

Let's say that there is a product "Product A" and the user buys this item 4 times, their shopping cart shows as "4" items in the basket, which is stored as: 假设有一个产品“产品A”,用户购买了4次该商品,他们的购物车在购物篮中显示为“ 4”个商品,存储为:

$items = [
  "Product A" => array (),
  "Product A" => array(),
  "Product B" => array()
];

When they view the shopping cart, I want it to therefore show: 当他们查看购物车时,我希望它显示:

Product:          Quantity:

"Product A"          2
"Product B"          1

Therefore, the question is, whether or not it is possible to do a array_unique with a count? 因此,问题是,是否可以用count做array_unique So, I could store all of the unique items but also get the number of items that they have ordered? 因此,我可以存储所有唯一商品,但还可以获取订购的商品数量? Or is there an alternative approach to this problem? 还是有替代方法解决此问题?

You may want to change the structure of your array: 您可能要更改数组的结构:

$items = [];

function addItem($name, array $data = []){
    global $items;
    $items[$name][] = $data;
}

function countItem($name){
    global $items;
    return count($items[$name]);
}

So $items will end up like this: 因此$items最终将像这样:

$items = [
    "Product A" => [
        array(),
        array(),
    ],
    "Product B" => [
        array()
    ]
];

$array[] = $element will create an empty array $array if it is undefined. $array[] = $element如果未定义,将创建一个空数组$array Similarly, $array["a"][] = $element will create an empty array $array["a"] if it is not defined yet. 同样,如果尚未定义$array["a"][] = $element则会创建一个空数组$array["a"]

Or if you only want to store a count, you have to use if(!isset($array["a"])) $array["a"] = 0; 或者,如果只想存储一个计数,则必须使用if(!isset($array["a"])) $array["a"] = 0; before incrementing it with $array["a"]++ . 在使用$array["a"]++递增它之前。

Following is the logic. 以下是逻辑。

1) Create a blank array of product cart. 1)创建产品购物车的空白数组。

2) While adding item to array, check array_key_exists() . 2)在将项目添加到数组时,请检查array_key_exists()

3) If does not exist, add item to array as key and quantity as value (this is quantity). 3)如果不存在,则将项添加到数组作为键,并将数量添加为值(这是数量)。

4) If exists, increase quantity by one. 4)如果存在,将数量增加一。

Thats it. 而已。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM