我正在使用会话变量构建一个购物车。我可以像这样将数组推入会话数组:
//initialize session cart array
$_SESSION['cart'] = array();
//store the stuff in an array
$items = array($item, $qty);
//add the array to the cart
array_push($_SESSION['cart'], $items);
到目前为止,一切顺利。问题是在从购物车中删除一个项目。当我尝试使用这个时,我得到一个数组到字符串转换错误。
//remove an array from the cart
$_SESSION['cart'] = array_diff($_SESSION['cart'], $items);
澄清一下,这里的问题是为什么上面的语句创建数组到字符串转换错误?
像这样存储一个对象数组怎么样?在我看来,这种方式比在数组
中对数组进行寻址要容易得多。$item = new stdClass();
$item->id = 99;
$item->qty = 1;
$item->descr = 'An Ice Cream';
$item->price = 23.45;
$_SESSION['cart'][$item->id] = $item;
从购物车中删除一个项目
unset($_SESSION['cart'][$item]);
重新访问项数据
echo $_SESSION['cart'][$item]->id;
echo $_SESSION['cart'][$item]->desc;
echo $_SESSION['cart'][$item]->price;
或者
$item = $_SESSION['cart'][$item];
echo $item->id;
echo $item->desc;
echo $item->price;
或者更好的
foreach ( $_SESSION['cart'] as $id => $obj ) {
echo $id ' = ' $obj->descr ' and costs ' . $obj->price;
}
修改现有信息
$_SESSION['cart'][$item]->qty += 1;
或
$_SESSION['cart'][$item]->qty = $newQty;
我建议这样做
$_SESSION['cart'] = array();
添加条目
$_SESSION['cart'][$item]= $qty;
然后使用items id来操作:
删除:
unset($_SESSION['cart'][$item]);
更改为已知数量值:
$_SESSION['cart'][$item]= $qty;
添加一个:
$_SESSION['cart'][$item] += 1;
一个条目的多个变量:
$_SESSION['cart'][$item]= array('qty'=>$qty,$descrip,$size,$colour);