Jump to content

simple shopping cart help


Synergic

Recommended Posts

I'm creating a simple, non-presistent shopping cart. Currently it allows a product ID and a qty. What i want is without re-writing the code below a simple way of adding a third variable such as a description. Any ideas? Since the array only accepts one associated field inside it i can't seem to figure how to add a third attribute.

[code] <?php




class ShoppingCart {

    var $items;
 


    function add_items($product_id, $qty, $desc)
    {
   
  $this->items[$product_id]=$qty;
 
 
 
 
 
    }

    function update_items($product_id, $qty)
    {
      if(array_key_exists($product_id, $this->items))
      {
          if($this->items[$product_id]>$qty)
          {
            $this->items[$product_id]-=($this->items[$product_id]-$qty);
          }
          if($this->items[product_id]<$qty)
          {
            $this->items[$product_id]+=abs($this->items[$product_id]-$qty);
          }
          if($qty==0)
          {
            unset($this->items[product_id]);
          }
      }
    }
 
    function remove_item($product_id)
    {
      if(array_key_exists($product_id, $this->items))
      {
          unset($this->items[$product_id]);
      }
    }

    function show_cart()
    {
      return $this->items;
    }

}

$cart = new ShoppingCart;

$cart->add_items("test", "2", "3");

//$cart->remove_item("Apples");


$cart_items=$cart->show_cart();

foreach($cart_items as $key=>$value)
{
    echo "$key $value<br>";
}






?>[/code]
Link to comment
Share on other sites

Either

[code]function add_items($product_id, $qty, $desc)
    {
   
  $this->items[$product_id] = array($qty, $desc);
    }
[/code]   
in which case get description by

[code]$desc = $this->items[$prod][1][/code]


or


[code]function add_items($product_id, $qty, $desc)
    {
   
  $this->items[$product_id] = array('qty' => $qty, 'desc' => $desc);
    }
[/code]   
in which case get description by

[code]$desc = $this->items[$prod]['desc'][/code]
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.