如何更新 Laravel 会话数组中的单个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30151030/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to update a single value in a Laravel Session Array?
提问by Faizuddin Mohammed
I have a Session array like this:
我有一个这样的 Session 数组:
[
{
"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.
我是初学者。请帮忙。谢谢。
回答by peterm
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"
}
]