这是我的问题。我有一个关联数组,希望键与传入函数的项对象的项ID匹配。如果项ID键在数组中不存在,我希望将项ID添加到购物车数组作为键,并将一个新数组
如果键已经存在,我只想更新通过索引项ID检索出来的存储在数组中的数量。
以下是我认为可以产生这些结果的代码(位于Cart.class.php中):
然而,当使用
我的问题是
["Item"=>$item,"Quantity=>1]
作为键值添加进去。如果键已经存在,我只想更新通过索引项ID检索出来的存储在数组中的数量。
以下是我认为可以产生这些结果的代码(位于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;
}
然而,当使用
var_dump($this->cart_items)
时,会输出以下内容: array(2){
[
0
] => NULL [
1
] => array(2) {
[
"Item"
] => object(stdClass)#2 (8) {
[
"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],第一个是null,尽管我使用了$this->cart_items[$item->ItemID] = array()
。
我的问题是我做错了什么,为什么id没有被用作数组中的键?
谢谢。