I made a system a while back which involves a basic shopping cart. The cart is a very simple OOP system which adds items by 1 quantity at a time. Here is the function for adding an item to the cart.
function add_item($itemid,$qty=1,$price = FALSE, $info = FALSE)
{
if($this->itemqtys[$itemid] > 0)
{ // the item is already in the cart..
// so we'll just increase the quantity
$this->itemqtys[$itemid] = $qty + $this->itemqtys[$itemid];
$this->_update_total();
} else {
$this->items[]=$itemid;
$this->itemqtys[$itemid] = $qty;
$this->itemprices[$itemid] = $price;
$this->iteminfo[$itemid] = $info;
}
$this->_update_total();
}
The problem with this is some of the products have variations (sizes, colours etc..) but when they chose a different variation in the same order, the products are not added correctly – all of the same product falling under one variation.
I thought it would be an idea to use multidimensional arrays, or arrays within arrays, to produce something like:
$this->iteminfo[$itemid][$var];
Getting the var from the product is not a problem, just im struggling with how to add the product to the cart with its variation, and updating the quantity of this product/variation combination only when the variation is added again. If a different variation is added, it would add the product in a new entry in the cart?
Hope this makes sense :/ Thanks
I would suggest using a single dimension(al) array, but rather than filling it with plain old ints and strings, place a object within it. It will be much more robust that way, and you can easily cycle through to get whatever you need – as well as being able to expand the object out further in the future.
Something like this would even work:
Then just pass the object instances of
itemToBuyrather than the arrays you are passing it at the moment.