Updating previous Session Array Laravel

99封情书 提交于 2019-12-11 12:59:28

问题


I have an issue on how can I update my Previous array ? What currently happening to my code is its just adding new session array instead of updating the declared key here's my code:

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);

回答1:


$items = Session::get('items', []);

foreach ($items as &$item) {
    if ($item['item_id'] == $id) {
        $item['item_quantity']--;
    }
}

Session::set('items', $items);



回答2:


I guess this will work for you if you are on laravel 5.0. But also note, that I haven't tested it on laravel 4.x, however, I expect the same result anyway:

//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));



回答3:


You can use Session::forget('key'); to remove the previous array in session.

And use Session::push to add new items to Session.



来源:https://stackoverflow.com/questions/24765487/updating-previous-session-array-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!