简体   繁体   中英

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:

$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? 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 = [
    "Product A" => [
        array(),
        array(),
    ],
    "Product B" => [
        array()
    ]
];

$array[] = $element will create an empty array $array if it is undefined. Similarly, $array["a"][] = $element will create an empty array $array["a"] if it is not defined yet.

Or if you only want to store a count, you have to use if(!isset($array["a"])) $array["a"] = 0; before incrementing it with $array["a"]++ .

Following is the logic.

1) Create a blank array of product cart.

2) While adding item to array, check array_key_exists() .

3) If does not exist, add item to array as key and quantity as value (this is quantity).

4) If exists, increase quantity by one.

Thats it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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