I am developing a shopping cart for my website. I have created an array for storing item details for items added to cart.
items[] is array which again contains array sized 5 to store id, name, req_qty, avail_qty and cost. Now everything is working fine, except deletion of item.
If I want to delete an item from cart, I need to delete the corresponding array containing id, name... I have used unset to remove the values from the array and array_values() to rearrange the array values. But could not solve the problem. The array size is not reduced, it remains unchanged.
Referece Code:
Code: Select all
class cart
{
var $items;
var $sub_total;
//var $total_items;
function cart()
{
$this->items = array();
$this->sub_total = 0;
}
function add_item($item_id,$item_name,$a_qty,$r_qty,$item_price)
{
// if not in cart
if(!isset($this->items[$item_id]))
{
//Add item to cart
$this->items[$item_id]['id'] = $item_id;
$this->items[$item_id]['name'] = $item_name;
$this->items[$item_id]['a_qty'] = $a_qty;
$this->items[$item_id]["r_qty"] = $r_qty;
$total_cost = $this->items[$item_id]["total_cost"] = $r_qty * $item_price;
$this->sub_total += $total_cost;
}
else
{
//Update item
$item_count = $this->items[$item_id]["r_qty"] += $r_qty;
$this->items[$item_id]["total_cost"] = $item_count * $item_price;
$new_cost = $r_qty * $item_price;
//Calculate subtotal
$this->sub_total += $new_cost;
}
}
function delete_item($item_id)
{
echo $item_id;
//Delete item from cart
$this->sub_total -= $this->items[$item_id]['total_cost'];
//echo $this->sub_total . "ghvhjbjhbb";
$this->items[$item_id] = array();
unset($this->items[$item_id]);
//$this->items = array_values($this->items);
echo "Item<br>";
print_r($this->items);
echo "<br>";
//$this->items[$item_id] = array();
}
}d11wtq | Please use
Code: Select all
tags when posting PHP code[/color]