简体   繁体   English

从会话数组中删除数组

[英]Removing an array from a session array

I am building a shopping cart using session variables. 我正在使用会话变量构建购物车。 I can push the array to the session array like this: 我可以将数组推送到会话数组,如下所示:

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

So far, so good. 到现在为止还挺好。 The problem is in removing an item from the cart. 问题在于从购物车中移除物品。 When I try to use this, I get a array to string conversion error. 当我尝试使用它时,我得到一个数组到字符串转换错误。

//remove an array from the cart
$_SESSION['cart'] = array_diff($_SESSION['cart'], $items);

To clarify, the question here is why is the above statement creating an array to string conversion error? 为了澄清,这里的问题是为什么上面的语句创建一个数组到字符串转换错误?

How about storing an array of objects like this. 如何存储像这样的对象数组。 In my opinion it is a lots easier to read the code this way than addressing arrays within arrays 在我看来,以这种方式阅读代码要比在数组中寻址数组容易得多

$item = new stdClass();
$item->id = 99;
$item->qty = 1;
$item->descr = 'An Ice Cream';
$item->price = 23.45;

$_SESSION['cart'][$item->id] = $item;

To remove an items from the cart 从购物车中删除商品

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

To re-access the items data 要重新访问项目数据

echo $_SESSION['cart'][$item]->id;
echo $_SESSION['cart'][$item]->desc;
echo $_SESSION['cart'][$item]->price;

Or even 甚至

$item = $_SESSION['cart'][$item];
echo $item->id;
echo $item->desc;
echo $item->price;

Or even better 甚至更好

foreach ( $_SESSION['cart'] as $id => $obj ) {
    echo $id ' = ' $obj->descr ' and costs ' . $obj->price;
}

To change existing info 要更改现有信息

$_SESSION['cart'][$item]->qty += 1;

or 要么

$_SESSION['cart'][$item]->qty = $newQty;

i suggest this approach 我建议这种方法

$_SESSION['cart'] = array();

to add an item 添加项目

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

then use the items id to manipulate: 然后使用项目ID来操作:

delete: 删除:

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

change to known qty value: 更改为已知的数值:

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

add one: 添加一个:

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

multiple variables for an item: 项目的多个变量:

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

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

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