合并两个数组时,属性 [name] 在 laravel 中的此集合实例上不存在
Property [name] does not exist on this collection instance in laravel when merging two arrays
在 laravel 中,我在控制器中使用数组合并时遇到了这个问题。我必须使用它,因为我想显示来自两个数组的数据并将它们显示在 laravel 中的一个 table 中,那么我该如何解决该错误以及它的实际含义是什么?
我的控制器
$array1=DB::table('table1')
->whereDate('created_at', Carbon::today())
->select('table1.name as name','table1.age as age')
->get();
$array2=DB::table('table1')
->leftJoin('table_2','table1.id','=','table2.table1_id')
->whereDate('new_date', Carbon::today())
->select('table1.name as name','table2.age as age')
->get();
$data=array_merge(array($array1,$array2));
return view('index')->with('records',$data)
我的观点
@foreach($records as $record)
<td>{{$record->name}}</td>
@endforeach
错误
Property [name] does not exist on this collection instance
因为箭头用于 objects 而不适用于 array
您应该使用 $record['name'],如果该数组具有此索引,它将为您显示
否则根本没有那个索引!
您正在以错误的方式合并数组结果...
您应该将数组作为参数而不是参数数组传递
$array1=DB::table('table1')
->whereDate('created_at', Carbon::today())
->select('table1.name as name','table1.age as age')
->get()->toArray();
$array2=DB::table('table1')
->leftJoin('table_2','table1.id','=','table2.table1_id')
->whereDate('new_date', Carbon::today())
->select('table1.name as name','table2.age as age')
->get()->toArray();
$data=array_merge($array1,$array2);
并确保使用方法 toArray()
将查询结果转换为数组。
在您的 blade 中,您应该将变量作为数组项访问,而不是 object:
$record['name']
尝试在 ->get() 之后添加 -> toArray()。
并在视图中使用 {{$record['name']}}。
并像这样使用数组合并:$data=array_merge($array1,$array2);
get()
returns 不是数组的集合,因此您应该使用 collection merge method
$data= $array1->merge($array2);
在 laravel 中,我在控制器中使用数组合并时遇到了这个问题。我必须使用它,因为我想显示来自两个数组的数据并将它们显示在 laravel 中的一个 table 中,那么我该如何解决该错误以及它的实际含义是什么? 我的控制器
$array1=DB::table('table1')
->whereDate('created_at', Carbon::today())
->select('table1.name as name','table1.age as age')
->get();
$array2=DB::table('table1')
->leftJoin('table_2','table1.id','=','table2.table1_id')
->whereDate('new_date', Carbon::today())
->select('table1.name as name','table2.age as age')
->get();
$data=array_merge(array($array1,$array2));
return view('index')->with('records',$data)
我的观点
@foreach($records as $record)
<td>{{$record->name}}</td>
@endforeach
错误
Property [name] does not exist on this collection instance
因为箭头用于 objects 而不适用于 array
您应该使用 $record['name'],如果该数组具有此索引,它将为您显示
否则根本没有那个索引!
您正在以错误的方式合并数组结果...
您应该将数组作为参数而不是参数数组传递
$array1=DB::table('table1')
->whereDate('created_at', Carbon::today())
->select('table1.name as name','table1.age as age')
->get()->toArray();
$array2=DB::table('table1')
->leftJoin('table_2','table1.id','=','table2.table1_id')
->whereDate('new_date', Carbon::today())
->select('table1.name as name','table2.age as age')
->get()->toArray();
$data=array_merge($array1,$array2);
并确保使用方法 toArray()
将查询结果转换为数组。
在您的 blade 中,您应该将变量作为数组项访问,而不是 object:
$record['name']
尝试在 ->get() 之后添加 -> toArray()。
并在视图中使用 {{$record['name']}}。
并像这样使用数组合并:$data=array_merge($array1,$array2);
get()
returns 不是数组的集合,因此您应该使用 collection merge method
$data= $array1->merge($array2);