简体   繁体   English

如何更新Laravel会话数组中的单个值?

[英]How to update a single value in a Laravel Session Array?

I have a Session array like this: 我有一个像这样的会话数组:

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

How can I update the quantity of a single item if I know the itemId ? 如果知道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'));

Output: 输出:

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

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

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