繁体   English   中英

从会话数组中删除数组

[英]Removing an array from a session array

我正在使用会话变量构建购物车。 我可以将数组推送到会话数组,如下所示:

//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;

然后使用项目ID来操作:

删除:

unset($_SESSION['cart'][$item]);

更改为已知的数值:

$_SESSION['cart'][$item]= $qty;

添加一个:

$_SESSION['cart'][$item] += 1;

项目的多个变量:

$_SESSION['cart'][$item]= array('qty'=>$qty,$descrip,$size,$colour);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM