从会话数组中删除数组

时间:2014-08-14 23:58:44

标签: php arrays session array-push

我正在使用会话变量构建购物车。我可以像这样将数组推送到会话数组:

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

为了澄清,这里的问题是为什么上面的语句创建一个数组到字符串转换错误?

2 个答案:

答案 0 :(得分:2)

如何存储像这样的对象数组。在我看来,以这种方式阅读代码要比在数组中寻址数组

容易得多
$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;

答案 1 :(得分:1)

我建议采用这种方法

$_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);
相关问题