php Laravel出口:尝试读取空值的属性“second_key

igetnqfo  于 2023-01-29  发布在  PHP
关注(0)|答案(1)|浏览(109)

我需要使用Laravel Export导出数据,但代码返回ErrorException:尝试读取null上的属性"second_key"
我的代码:

<?php
namespace App\Admin\Extensions;
use Encore\Admin\Grid\Exporters\ExcelExporter;
use Maatwebsite\Excel\Facades\Excel;
use Maatwebsite\Excel\Concerns\FromQuery;
use Maatwebsite\Excel\Concerns\WithMapping;
use Maatwebsite\Excel\Concerns\ShouldAutoSize;
class DataExporter extends ExcelExporter implements FromQuery, WithMapping, ShouldAutoSize
{
protected $fileName = 'Export Data.xlsx';
    public function headings(): array
    {
        return [
            'ID',
            'Title',
            'Status',
            'Gender',
            'Data',
        ];
    }
    public function map($data): array
    {
        return [
            $data->id,
            $data->title,
            $data->status,
            $data->gender,
            $data->json_data->second_key, // <-- Here's the error
        ];
    }

}

我试着用这个来检查:
print_r(json_encode($data->json_data));
这就是结果

{
      "id": 282,
      "second_key": "second_value",
      "third_key": "6200",
      "fourth_key": "0000",
      "fifth_key": 28
}

我也这么做过:

return [
     $data->id,
     $data->title,
     $data->status,
     $data->gender,
     $data->json_data //Without "second_key"
];

excel单元格返回相同的结果:

{
      "id": 282,
      "second_key": "second_value",
      "third_key": "6200",
      "fourth_key": "0000",
      "fifth_key": 28
}
wh6knrhe

wh6knrhe1#

正如@dbf在评论部分所说,我必须处理空行,我在数据库中检查了好几次,可能我错过了那一个空行,无论如何,这是我处理那些值的方法:

if (!isset($data->json_data->second_key)) {
    $second_key = '-';
} else {
    $second_key = $data->json_data->second_key;
}

return [
     $data->id,
     $data->title,
     $data->status,
     $data->gender,
     $second_key
];

相关问题