Laravel 4导出Excel多维查询结果
我试图让PHPExcel(而不是Laravel的包装: https : //github.com/Maatwebsite/Laravel-Excel )导出我的观点。 我正在运行的查询将多行作为multidimensional array返回(我使用DB :: select和绑定方式,因为对于Fluent来说查询有点复杂)
结果如下所示:
array(3) { [0]=> object(stdClass)#224 (3) { ["name"]=> string(13) "Administrator" ["TotalRequest"]=> string(6) "100.00" ["TotalGiven"]=> string(6) "150.00" } [1]=> object(stdClass)#226 (3) { ["name"]=> string(14) "Beta Alpha Psi" ["TotalRequest"]=> string(6) "363.00" ["TotalGiven"]=> string(6) "200.00" } [2]=> object(stdClass)#227 (3) { ["name"]=> string(30) "Student Government Association" ["TotalRequest"]=> string(7) "1225.00" ["TotalGiven"]=> string(6) "620.00" } }
Laravel-Excel包只需要一个$ data数组(),所以我很困惑如何将我的multidimensional array转换为我的视图。 如果我使用替代scheme,我可以得到它的工作
View::make(xxxx)->with('example', $example)
我是否忽略了如何将$ data作为一个数组传递给对象?
这不是一个多维array
而是一个对象array
。 如果你使用类似这样的方式将array
传递给你的视图:
View::make('xxxx')->with('example', $example)
然后在你的视图中,你可以使用@foreach
来循环它,就像这样:
@foreach($example as $item) {{ $item->name }} {{ $item->TotalRequest }} {{ $item->TotalGiven }} @endforeach
因为该数组包含多个stdClass
对象,并且第一个对象是( 0
):
{ ["name"]=> string(13) "Administrator" ["TotalRequest"]=> string(6) "100.00" ["TotalGiven"]=> string(6) "150.00" }
所以,你也可以使用类似$example[0]
方法从$example
数组中检索第一个对象,并检索第二个对象,你可以使用$example[1]
等等。
那么我build议你简单地改变取模式直接返回一个数组,像下面的方法
public function getQueryResult($returnQueryAs = null)' { $tablename = 'YourAwesomeTable'; if($returnQueryAs == 'array') { DB::connection()->setFetchMode(PDO::FETCH_ASSOC); } return DB::table($tablename)->get(); }
然后做这样的事情
public function exportAsExcel() { $filename = 'nameoffile'; $data = $this->getQueryResult($as = 'array'); Excel::create($filename, function($excel) use ($filename, $data) { // Set the title $excel->setTitle($filename); // Chain the setters $excel->setCreator('Damilola Ogunmoye'); $excel->sheet('SHEETNAME', function($sheet) use ($data) { $sheet->fromArray($data); }); })->download('xls'); }
这将得到一个关联数组,而不是一个stdClass对象,您可以直接传递。