简体   繁体   English

如何计算多维数组中每个唯一数组的数量? 的PHP

[英]How do I count the number of each unique array inside a multidimentional array? PHP

I'd like to build a simple shopping cart using arrays. 我想使用数组构建一个简单的购物车。 I need to display each unique item in the shopping cart aswell as the quantity of each item along side. 我需要显示购物车中的每个唯一商品以及旁边的每个商品的数量。

My initial cart array might look like this: 我的初始购物车数组可能如下所示:

$cart=

array(

         array(2003,100,"Table")
        ,array(2003,100,"Table")
        ,array(2003,100,"Table")
        ,array(2004,200,"Chair")
        ,array(2004,200,"Chair")

      );

The first value in each array is the product_id, then the price & then the product name. 每个数组中的第一个值是product_id,然后是价格和产品名称。

How do I print each unique item once aswell as the quantity of each along side? 我如何一次打印每个唯一的项目以及每个项目的数量?

Thanks in advance. 提前致谢。

$new_cart = array();

foreach($cart as $product) {
    if(!isset($new_cart[$product[0]])) {
      $new_cart[$product[0]] = array('quantity' => 1, 'label' => $product[2], 'price'        => $product[1]);
    }
    else {
      $new_cart[$product[0]]['quantity']++;
    }
}

I strongly suggest using associative arrays for this though. 我强烈建议为此使用关联数组。 Your problem is the way you are storing the values. 您的问题是存储值的方式。 Try using something like this: 尝试使用如下所示的内容:

$cart_items = array(
  2004 => array('quantity' => 3, 'label' => 'Leather Chair', 'price' => 200),
  2901 => array('quantity' => 1, 'label' => 'Office Desk', 'price' => 1200),

);

When a user updates a quantity or adds an existing product simply increment the quantity. 当用户更新数量或添加现有产品时,只需增加数量即可。

You could simply iterate the array and use the product ID as key to count the amounts: 您可以简单地迭代数组并使用产品ID作为键来计算数量:

$amounts = array();
foreach ($cart as $item) {
    if (!isset($amounts[$item[0]])) $amounts[$item[0]] = 0;
    $amounts[$item[0]]++;
}

But it would be easier if your cart just stores the product IDs and amounts, so: 但是,如果您的购物车仅存储产品ID和数量会更容易,那么:

array(
    2003 => 3,
    2004 => 2
)

This is actually what the algorithm above is doing. 这实际上就是上面的算法正在做的事情。 But with this, you have all the information you need (product ID and amount). 但是,有了这个,您便拥有了所需的所有信息(产品ID和数量)。

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

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