【问题标题】:Remove element from session array in laravel 5从 laravel 5 中的会话数组中删除元素
【发布时间】:2015-06-15 21:56:18
【问题描述】:

我是 Laravel 5 的新手,正在尝试通过自学来制作一个电子商务 Web 应用程序。

我有以下一系列产品:

array:2 [▼
  0 => array:4 [▼
    "productId" => 3
    "quantity" => 2
    "productName" => "Testing Product 3"
    "productRate" => 275.0
  ]
  1 => array:4 [▼
    "productId" => 2
    "quantity" => 2
    "productName" => "Testing Product 2"
    "productRate" => 180.0
  ]
]

现在,当用户单击购物车模板视图中的 x 链接时,它确实会从会话中删除产品,但也会在下一页重新加载时删除会话购物车的完整数组。

这是删除产品的控制器:

public function destroy($id) {

    if ( \Session::has( 'cart' ) && is_array( \Session::get('cart') ) ) {
        $cart = \Session::get('cart');
            
        for ($i=0; $i < count($cart); $i++) {
            foreach ($cart[$i] as $key => $value) {
                if ( $key === 'product' && $value == $id ) {
                    unset( $cart[$i] );
                }
            }
        }       
        return redirect('/cart')->with('cart', $cart);
    }
}

我也试过这样:

unset( $cart[$i][$key] )

但这给了我undefined index 错误。

请指导我在哪里犯了错误以及解决方法是什么。

更新 1

这里是索引函数:

public function index() {
    $cart = \Session::get('cart');
    return view('cart.index')->with('cart', $cart);
}

更新 2: 根据discussion,这里是销毁函数:

public function destroy($id) {

    if ( \Session::has( 'cart' ) && is_array( \Session::get('cart') ) ) {
        $cart = \Session::get('cart');
        
        foreach ($cart as $index => $product) {
            if ($product['productId'] == $id) {
                unset($cart[$index]);
            }
        }
        session(['cart' => $cart]);
        return redirect('/cart');
    }
}

【问题讨论】:

  • $id 的值是多少?是productId 还是Array Index
  • 它是productId

标签: php arrays session laravel laravel-5


【解决方案1】:

我建议您使用foreach 而不是for 来循环遍历数组。因为如果数组键不是以0 开头或者有任何像0,1,3 这样的跳过数组键,您可能会收到错误。

foreach ($cart as $index => $product) {
  if ($product['productId'] == $id) {
     unset($cart[$index]);
   }
}
session(['cart' => $cart]);

我只是更新代码以将$cart 值(删除某些产品后)更新回会话。

更新 redirect function之后我们不需要with function

return redirect('/cart')->with('cart', $cart);

return redirect('/cart');

【讨论】:

  • 它会做什么?我尝试了您的代码,我得到的是:使用相同会话重新加载页面,然后在下一页加载时,会话中没有数据。
  • 你取消评论unset 行了吗?我刚刚更新了我的代码。
  • 又试了一次,这次成功了,但是再次重新加载页面时,会话消失了。我的意思是根本没有产品。
  • 你重新加载了哪个页面?
  • 能否用索引操作代码 (/cart) 更新问题?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-30
  • 1970-01-01
  • 2017-08-23
  • 1970-01-01
  • 2019-12-31
  • 1970-01-01
相关资源
最近更新 更多