Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/248.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 会话中的Laravel存储阵列_Php_Laravel_Laravel 5.2 - Fatal编程技术网

Php 会话中的Laravel存储阵列

Php 会话中的Laravel存储阵列,php,laravel,laravel-5.2,Php,Laravel,Laravel 5.2,在会话中存储数组时遇到了困难。我正在做一个购物车,但它似乎不起作用 public function __construct(){ $product = array(1,2,3,4); Session::push('cart', $product); } 然后像这样在视图中检索它 {{Session::get('cart')}} htmlentities() expects parameter 1 to be string, array given 然而,我不断得到这样的错误 {

在会话中存储数组时遇到了困难。我正在做一个购物车,但它似乎不起作用

public function __construct(){

  $product = array(1,2,3,4);
  Session::push('cart', $product);

}
然后像这样在视图中检索它

{{Session::get('cart')}}
htmlentities() expects parameter 1 to be string, array given
然而,我不断得到这样的错误

{{Session::get('cart')}}
htmlentities() expects parameter 1 to be string, array given

关于如何创建存储项目数组的购物车的任何线索和建议。

您正在会话中存储一个数组,并且由于
{{}
需要一个字符串,因此不能使用
{{session::get('cart')}
来显示该值

{{$var}}
与编写
echo-htmlentities($var)
相同(一个非常简单的示例)

相反,您可以执行以下操作:

@foreach (Session::get('cart') as $product_id)
    {{$product_id}}
@endforeach

如果需要将会话中的数组用作字符串,则需要使用如下集合:

$product = collect([1,2,3,4]);
Session::push('cart', $product);
[
    0 => [1,2,3,4]
]

当您在htmls中使用
{{Session::get('cart');}}}
时,这将使它工作起来。请注意
Session::push
,因为它将始终在会话中附加新产品。您应该使用
Session::put
,以确保产品始终处于更新状态。

如果在会话中最初创建阵列时使用“推送”,则阵列将如下所示:

$product = collect([1,2,3,4]);
Session::push('cart', $product);
[
    0 => [1,2,3,4]
]
相反,您应该使用“put”:

$products = [1,2,3,4];
$request->session()->put('cart', $products);
任何后续值都应推送到会话数组上:

$request->session()->push('cart', 5);

您可以在会话中声明数组,如
$cart=session('data',[])


您可以使用

$product = array(1,2,3,4);
Session::put('cart.product',$product);

您也可以这样做:

  $data = collect($Array); 
  Session()->put('data', $data);
  return view('pagename');

我很好奇为什么集合或$request->all()可以通过{{}使用?htmlentities是否也通过了它们?@Nello Collections提供了一个用于处理数组的包装器。如果尝试
回显$collection
或使用
{{{$collection}}
,则集合将使用方法自动处理此问题。
$request->all()。我已经更正了代码。