Php 更新以前的会话数组Laravel

Php 更新以前的会话数组Laravel,php,arrays,laravel,laravel-4,Php,Arrays,Laravel,Laravel 4,我对如何更新以前的阵列有疑问? 我的代码目前的情况是,它只是添加了新的会话数组,而不是更新声明的密钥。以下是我的代码: foreach ($items_updated as $key => $added) { if ($id == $added['item_id']) { $newquantity = $added['item_quantity'] - 1; $update = array( 'item_id' =&g

我对如何更新以前的阵列有疑问? 我的代码目前的情况是,它只是添加了新的会话数组,而不是更新声明的密钥。以下是我的代码:

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

您可以使用会话::忘记('key')删除会话中的上一个数组


并使用
Session::push
向Session添加新项目。

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

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

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

Session::set('items', $items);
//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()->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)

我需要的是使用相同的项目Id再次保存,但使用新的数量,所以我认为session::forget('key'))不是解决方案。我不确定您试图做什么,但我可以看到,当您循环时,您将覆盖数组的内容
$update
,我建议使用array\u push;也许是像
$update[]
这样的东西,它可以工作。谢谢你,约瑟夫!!!但是,$items作为&$item是什么呢?我想理解它,谢谢。符号的意思是它指向单个项目数组,而不是副本。如果将
$items作为$item
执行,则
$item
变量将在
$items
数组中保存该项的副本,并且减少其
item\u quantity
属性不会对
$items
数组中的项产生任何影响。