dongxindu8753 2018-05-17 10:01
浏览 43
已采纳

Laravel 4.2:在会话中保留多维数组数据

In my laravel 4.2 application, i want to store the cart item details in session.

cartId =>[
            0 => [
                productId => x,
                quantity  => y
            ],
            1 => [
                productId => u,
                quantity  => v
            ],
            2 => [
                productId => l,
                quantity  => m
            ]

         ]

I didn't found a way except this

Session::push('user.teams', 'developers');

for storing as array in session. but the same is not applicable here

  • 写回答

2条回答 默认 最新

  • doujiebo9849 2018-05-18 13:03
    关注

    Looks like you can insert the array directly in the session.

    $someArray = ['name' => 'John Doe', 'username' => 'jdoe'];
    
    Session::put('user', $someArray);
    

    When you want to retrieve its value just need to:

    $user = Session::get('user');
    echo $user['name'] // output: John Doe
    

    Same applicable for multidimensional array...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
  • dsqbh42082 2018-05-18 13:12
    关注

    You can just store the information in the key required, such as:

    $cartDetails = [ 
                     0 => [
                           productId => x,
                           quantity  => y
                     ],
                     1 => [
                           productId => u,
                           quantity  => v
                     ],
                     2 => [
                           productId => l,
                           quantity  => m
                     ]
                   ];
    
    Session::put('cart', $cartDetails);
    

    Each user will have it's own cart, can you can validate with Session::has('cart') and Session::get('cart') will get you the content of $cartDetails.

    Session::forget('cart') will erase the key 'cart' from the Session, meaning Session::has('cart') == false and Session::get('cart') is null

    If you plan on using key's as Id's (Something among the lines of Session::put($cartId, $cartDetails)), I wouldn't advise as later on, if you need to add something with the same logic, you will compromise the Session's key and possibly, overwrite it. Same applies if someone else takes a look at the code (or even you in a not-so-long future) and need to read the code, there isn't a clear perception of whats in the session unless you read the whole function. (IMO)

    https://laravel.com/docs/4.2/session

    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 java连接sqlserver有问题
  • ¥15 yolov8 如何调cfg参数
  • ¥15 这个四人抢答器代码哪儿有问题?仿真程序怎么写?
  • ¥15 burpsuite密码爆破
  • ¥15 关于#ubuntu#的问题,如何解决?(相关搜索:移动硬盘)
  • ¥15 scikit安装之后import不了
  • ¥15 Ros2编译一个使用opencv的c++节点的时候,报了这个错误,请问怎么解决啊
  • ¥15 人脸识别相关算法 YOLO,AI等
  • ¥15 spark问题方便加V17675797079
  • ¥15 Python代码不打印的原因