【问题标题】:How to update a single value in a Laravel Session Array?如何更新 Laravel 会话数组中的单个值?
【发布时间】:2015-05-10 11:49:20
【问题描述】:

我有一个这样的 Session 数组:

[
    {
        "itemId": "1",
        "itemQuantity": "3",
        "itemName": "Item_name1"
    },
    {
        "itemId": "2",
        "itemQuantity": "2",
        "itemName": "Item_name2"
    }
]

如果知道itemId,如何更新单品数量?

我知道这样做的一种方法是获取整个数组,循环遍历数组,进行更新并将整个数组“放入”回会话中。 这是唯一的方法吗?

我是初学者。请帮忙。 谢谢。

【问题讨论】:

  • 如果您使用的是阵列会话驱动程序,恐怕这是唯一的选择。
  • 我还可以使用什么其他驱动程序?谢谢!
  • 你好。出于好奇,您的itemId 是自动递增的吗?如果是,您是如何实现的?

标签: php session laravel laravel-5


【解决方案1】:

对象是通过引用传递的,所以你可以简单地做到这一点。

foreach(Session::get('cart') as $item) {
    if ($item->itemId == '2') { // say we  want to double the quantity for itemId 2
        $item->itemQuantity = $item->itemQuantity * 2;
        break;
    }
}
dd(Session::get('cart'));

输出:

array:2 [▼
  0 => {#162 ▼
    +"itemId": "1"
    +"itemQuantity": "3"
    +"itemName": "Item_name1"
  }
  1 => {#163 ▼
    +"itemId": "2"
    +"itemQuantity": 4  <<--- the quantity has been doubled
    +"itemName": "Item_name2"
  }
]

【讨论】:

  • @peterm 我正在尝试类似的方法,但在 `$item->itemQuantity = $item->itemQuantity * 2; `
  • @peterm 是的,我只是不确定为什么会这样,因为我的代码是基于你的:foreach(Session::get('cart.program') as $item){ if ($item-&gt;id == '1xxx') { $item-&gt;segment_weekday = '9'; break; } }
  • @peterm var_dump(Session::get('cart.program')): array (size=2) 0 =&gt; array (size=1) 'id' =&gt; string '1' (length=1) 1 =&gt; array (size=1) 'id' =&gt; string '1xxx' (length=4)
  • @peterm 感谢您的帮助。我可以访问数组成员,只是不知道如何通过引用&amp;$item 传递$item 以保存回会话。
  • @peterm 在stackoverflow.com/questions/31887608/…创建了一个新问题
猜你喜欢
  • 2017-06-10
  • 1970-01-01
  • 2020-06-06
  • 2020-10-11
  • 2020-03-25
  • 1970-01-01
  • 2018-04-16
  • 2017-01-07
  • 1970-01-01
相关资源
最近更新 更多