【问题标题】:Removing an array from a session array从会话数组中删除数组
【发布时间】:2014-10-08 18:36:03
【问题描述】:

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

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

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

【问题讨论】:

  • 任何理由使用array_push 超过$_SESSION['cart'][]= $items;
  • 没那么快——根本不是重复的。在发布之前检查您的信息。
  • 使用项目 id 作为键并取消设置
  • " 注意:如果你使用 array_push() 向数组添加一个元素,最好使用 $array[] = 因为这样就没有调用函数的开销。"

标签: php arrays session array-push


【解决方案1】:

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

$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 变量中重新合成属性来重构对象。您只需执行 $_SESSION['cart'] = serialize($cartObj); See this documentation
  • 这就是我最初搞砸的原因。我开始尝试使用一个对象,但由于对象有方法而出错。我终于这样做了, foreach($_SESSION['cart'] as $k => $v) { if ($v == $itemID) unset($_SESSION['cart'][$k]);哪个有效,但我仍然想知道为什么我使用 array_diff(); 得到转换错误;
  • 像我之前建议的那样做一个print_r(array_diff($_SESSION['cart'], $items));。我敢打赌,它对数组的深入程度不足以满足您的期望。
  • 你可以试试array_diff($_SESSION['cart'][], $items) 可能会奏效。
【解决方案2】:

我建议这种方法

$_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);

【讨论】:

  • 而使用这种方法,你将如何添加额外的变量,即$price、$descr等?
猜你喜欢
  • 1970-01-01
  • 2015-08-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多