views:

34

answers:

2

Hi,

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.

How do I print each unique item once aswell as the quantity of each along side?

Thanks in advance.

+1  A: 

You could simply iterate the array and use the product ID as key to count the amounts:

$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:

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).

Gumbo
Great! You're right, it does make more sense if the array stores the quantity.
matt
+2  A: 
$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.

Keyo
Thank you! This makes a lot of sense. I can immediately see how it would be easier to use an associative array.
matt
You should accept the answer!
Axsuul