0

目前我可以json从我的excel文件中获取数据,格式如下

sample.xlsx

    $excel = Importer::make('Excel');
    $excel->hasHeader(true);
    $excel->load($savePath.$fileName);
    $collection = $excel->getCollection();

    if(sizeof($collection[1]) == 5)
    {
        return $collection;
    }
    else
    {
        return redirect()
        ->back()
        ->with(['errors'=> [0=> 'Please provide date in file according to your format.']])
        ->with('modal',$modal);
    }

输出

[{"id":1,"first_name":"j.doe17","last_name":"Jun Doe","email":"j.doe@gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}},{"id":2,"first_name":"j.doe18","last_name":"Jun Doe","email":"jan.doe@gmail.com","birthdate":{"date":"1996-09-07 00:00:00.000000","timezone_type":3,"timezone":"Asia\/Taipei"}}]

现在我正在尝试使用此代码,只需将这些json数据插入到我的数据库表中 >tbl_sampleimport

         foreach ($collection->toArray() as $key => $value)  {
            foreach ($value as $row) {
                $insert_data[] = array(
                    'first_name'  => $row['first_name'],
                    'last_name'  => $row['last_name'],
                    'email'  => $row['email'],
                    'birthdate'  => $row['birthdate'],
                    'created_at'  => now(),
                    'updated_at'  => now(),
                );

            }
        }
        DB::table('tbl_sampleimport')->insert($insert_data);

我的桌子tbl_sampleimport

在此处输入图像描述

但这给了我这样的错误Illegal string offset 'first_name'

Laravel : v5.8.*

cyber-duck/laravel-excel

4

1 回答 1

1

用来json_decode()转换成array

$arr = json_decode($collection, true);
foreach($arr as $row) {
    $insert_data[] = array(
          'first_name'  => $row['first_name'],
          'last_name'  => $row['last_name'],
          'email'  => $row['email'],
          'birthdate'  => $row['birthdate']['date'],
          'created_at'  => now(),
          'updated_at'  => now(),
     );
}
于 2019-11-22T04:16:55.170 回答