Here is my problem. I have an associative array and I would like the keys to match the identifier of the element of the object of the object passed to the function. If the key of the id element does not already exist in the array, I would like to add the element identifier as the key to the basket array along with the new array ["Item"=>$item,"Quantity=>1]as the key value.
If the key already exists, I just would like to update the amount stored in the array, which will be retrieved by indexing the basket array with the item ID.
Below is the code that I thought would give these results (located in Cart.class.php):
private $cart_items = array();
public function add_to_cart($item, $quantity = 1){
if(!isset($item) || !isset($item->ItemID)){
throw new Exception("Error adding item to cart");
}
if(!array_key_exists($item->ItemID,$this->cart_items)){
$this->cart_items[$item->ItemID] = array("Item"=>$item,"Quantity"=>$quantity);
}else{
$this->cart_items[$item->ItemID]["Quantity"] += $quantity;
}
$this->number_of_cart_items+=$quantity;
}
However, when used, the var_dump($this->cart_items)following is displayed:
array(2){
[
0
] => NULL [
1
] => array(2) {
[
"Item"
] => object(stdClass)
[
"ItemID"
] => int(11) [
"ItemName"
] => string(18) "Kids check T-Shirt" [
"ShortDescription"
] => string(20) "A kids check T-Shirt" [
"LongDescription"
] => string(51) " A kids check T-shirt perfect for formal occasions!" [
"ItemPrice"
] => float(33.59) [
"ImagePath"
] => string(51) "kozzi-26129586-1591x2387.jpg" [
"QuantityAvailable"
] => int(100) [
"ItemSupplier_SupplierID"
] => int(1)
} [
"Quantity"
] => int(1)
}
}
, $item->ItemID ( , [0] [1], , $this->cart_items[$item->ItemID] = array(),
, , ?