类stdClass的对象不能被转换为string – laravel

我正在关注这个文档

在我的laravel 4项目中实现导出到Excel。

所以我想这样从数组中生成excel文件:

//$results is taken with db query $data = array(); foreach ($results as $result) { $result->filed1 = 'some modification'; $result->filed2 = 'some modification2'; $data[] = $result; } Excel::create('Filename', function($excel) use($data) { $excel->sheet('Sheetname', function($sheet) use($data) { $sheet->fromArray($data); }); })->export('xls'); 

但是这引起了exception:

  Object of class stdClass could not be converted to string 

我究竟做错了什么 ?

更新:

试过这个:

 $data = get_object_vars($data); 

这导致:

 get_object_vars() expects parameter 1 to be object, array given 

这个:

 $data = (array)$data; 

导致最初的错误。

$data确实是一个数组,但它是由对象组成的。

在创build之前将其内容转换为数组:

 $data = array(); foreach ($results as $result) { $result->filed1 = 'some modification'; $result->filed2 = 'some modification2'; $data[] = (array)$result; #or first convert it and then change its properties using #an array syntax, it's up to you } Excel::create(.... 

在一行代码中试试这个简单:

 $data= json_decode( json_encode($data), true); 

希望能帮助到你 :)

您可能需要先将对象更改为数组。 我不知道export是什么,但我认为它期待一个数组。

你可以使用

get_object_vars()

或者,如果它是一个简单的对象,你可以只是forms化它。

$arr = (array) $Object;

如果你有一个stdClass对象的集合,你可以试试这个:

 $data = $data->map(function ($item){ return get_object_vars($item); });