如何更新Laravel会话数组中的单个值? [英] How to update a single value in a Laravel Session Array?

查看:85
本文介绍了如何更新Laravel会话数组中的单个值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个像这样的Session数组:

I have a Session array like this:

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

如果我知道itemId,如何更新单个项目的数量?

How can I update the quantity of a single item if I know the itemId?

我知道执行此操作的一种方法是获取整个数组,遍历整个数组,进行更新,然后将整个数组放入"会话. 这是唯一的方法吗?

I know that one way of doing this would be to fetch the whole array, loop through the array, make the updates and 'put' the entire array back into the session. Is this the only way?

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

I'm a beginner. Please help out. Thanks.

推荐答案

对象是通过引用传递的,因此您可以轻松地做到这一点.

Objects are passed by reference so you can simply do this.

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"
  }
]

这篇关于如何更新Laravel会话数组中的单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆