更新以前的会话数组 Laravel

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/24765487/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 09:49:10  来源:igfitidea点击:

Updating previous Session Array Laravel

phparrayslaravellaravel-4

提问by Martney Acha

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

回答by Joseph Silber

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

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

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

回答by Ramesh Dahiya

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

您可以使用Session::forget('key');删除会话中的前一个数组。

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

并用于Session::push向会话添加新项目。

回答by user28864

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:

如果您使用的是 laravel 5.0,我想这对您有用。但还要注意,我还没有在 laravel 4.x 上测试过它,但是,无论如何我都希望得到相同的结果:

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