laravel 调用未定义的方法 stdClass::toArray()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/47204041/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 16:56:21  来源:igfitidea点击:

Call to undefined method stdClass::toArray()

phplaravelexport-to-excellaravel-blade

提问by user8665248

I want to export the table but not all fields have to be exported. sorry my english is not very good...

我想导出表,但并非所有字段都必须导出。对不起我的英语不是很好...

function excel

功能 excel

public function excel()
    {
        $rekanan_internal = rekanan_internal::all();
        $selects = DB::table('rekanan_internal')->select('nama','description','pic','contact')->get();
        $selectsArray = [];
        $selectsArray = ['nama','description','pic','contact'];
        foreach ($selects as $select) 
        {
            $selectsArray = $select->toArray();
        } 

        Excel::create('rekanan_internal', function($excel) use($rekanan_internal){
            $excel->sheet('sheet1',function($sheet) use($selectsArray){
                $sheet->fromArray($rekanan_internal);
            });
        })->download('xlsx');
    }

getting error

出错

FatalErrorException in ExportController.php line 31: Call to undefined method stdClass::toArray()

ExportController.php 第 31 行中的 FatalErrorException:调用未定义的方法 stdClass::toArray()

回答by Jerodev

DB::table('xxxx')->get()will return a collection of stdClass. stdClasshas no function toArray().

DB::table('xxxx')->get()将返回stdClass. stdClass没有功能toArray()

You probably want to make an array of the entire collection, in this case, you can replace the for loop with the following:

您可能想要制作整个集合的数组,在这种情况下,您可以将 for 循环替换为以下内容:

$selectsArray = $selects->toArray();

This is because a collection does have a function called toArray.

这是因为集合确实有一个名为toArray.

Update:
You could even shorten your code to the following:

更新:
您甚至可以将代码缩短为以下内容:

$selectsArray = DB::table('rekanan_internal')
    ->select('nama','description','pic','contact')
    ->get()
    ->toArray();

Update 2:
For Laravel versions smaller than 5.3, you don't even need to cast the result to an array because the result is an array.

更新 2:
对于小于 5.3 的 Laravel 版本,您甚至不需要将结果转换为数组,因为结果是一个数组。

$selectsArray = DB::table('rekanan_internal')
    ->select('nama','description','pic','contact')
    ->get()