我有一个关于如何更新我的上一个数组的问题?目前我的代码只是添加了新的会话数组,而不是更新声明的键,这是我的代码:
foreach ($items_updated as $key => $added)
{
if ($id == $added['item_id'])
{
$newquantity = $added['item_quantity'] - 1;
$update = array(
'item_id' => $items['item_id'],
'item_quantity' => $newquantity,
);
}
}
Session::push('items', $updated);
$items = Session::get('items', []);
foreach ($items as &$item) {
if ($item['item_id'] == $id) {
$item['item_quantity']--;
}
}
Session::set('items', $items);
如果在会话数组中有嵌套数组。您可以使用以下方式更新会话:$session()->put('user.age',$age);
假设在会话
中有以下数组结构$user = [
"name" => "Joe",
"age" => 23
]
session()->put('user',$user);
//updating the age in session
session()->put('user.age',49);
如果您的会话数组是n个数组深度,那么使用点(.)后跟键名来到达第n个值或数组,如session->put('user.comments.likes',$likes)
我想这将为您工作,如果你是在laravel 5.0。但也要注意,我还没有在laravel 4上测试过。但是,无论如何,我希望得到相同的结果:
//get the array of items (you will want to update) from the session variable
$old_items = 'Session::get('items');
//create a new array item with the index or key of the item
//you will want to update, and make the changes you want to
//make on the old item array index.
//In this case I referred to the index or key as quantity to be
//a bit explicit
$new_item[$quantity] = $old_items[$quantity] - 1;
//merge the new array with the old one to make the necessary update
'Session::put('items',array_merge($old_items,$new_item));
您可以使用Session::forget('key');
删除会话中的前一个数组。
并使用Session::push
向Session添加新项