【问题标题】:ErrorException (E_WARNING) Illegal string offset 'customerid'ErrorException (E_WARNING) 非法字符串偏移 'customerid'
【发布时间】:2019-07-10 06:31:56
【问题描述】:

我是 laravel 框架的新手。我收到一个错误

错误异常 (E_WARNING) 非法字符串偏移 'customerid'

我尝试导入一个 excel 文件并在同一页面的数据表中显示数据。我收到一个错误:

调用未定义的方法 maatwebsite/Excel/Excel::load()。

为了修复这个错误,我将maatwebsite/excel 版本从3.1 降级为~2.1.0,然后我使用composer update 更新了作曲家。然后我得到另一个错误“继续”目标开关相当于中断 - 我通过在 OLE.php 文件中更改 continue to continue 2 来修复它。

现在我遇到了一个新错误

"错误异常 (E_WARNING) 非法字符串偏移 'customerid'"

public function import_csv(Request $request)
{
    $this->validate($request, [
        'select_file' => 'required|mimes:xls,xlsx',
    ]);

    $path = $request->file('select_file')->getRealPath();

    $data = Excel::load($path)->get();

    if ($data->count() > 0) {
        foreach ($data->toArray() as $key => $value) {
            foreach ($value as $row) {
                $insert_data[] = [
                    'customerid'  => $row['customerid'],
                    'enquiryid'   => $row['enquiryid'],
                    'productid'   => $row['productid'],
                    'productname' => $row['productname'],
                    'quantity'    => $row['quantity'],

                ];
            }
        }

        if (!empty($insert_data)) {
            DB::table('enquiryproducts')->insert($insert_data);
        }
    }

    return back()->with('success', 'Excel Data Imported successfully.');
}

import_csv.blade.php

<form id="upload_csv_form" action="{{ url('/import_csv/import') }}" method="POST" enctype="multipart/form-data">
    @csrf
    <div class="row">
        <div class="col-lg-6 col-md-12">
            <fieldset class="form-group">
                <input type="file" name="select_file" accept=".csv" class="form-control-file" id="select_file">
            </fieldset>
            <button type="submit" name="upload_csv" class="btn btn-success">Upload Enquiry Products</button>
        </div>
    </div>
</form>

【问题讨论】:

标签: php laravel


【解决方案1】:

您不必为 $value 创建另一个 foreach 循环。

试试这个:

if($data->count() > 0)
{
    foreach($data as $key => $value)             
    $insert_data[] = array(
       'customerid'   => $value['customerid'],
       'enquiryid'   => $value['enquiryid'],
       'productid'   => $value['productid'],
       'productname' => $value['productname'],
       'quantity'    => $value['quantity'],    
    );                
}

【讨论】:

  • 谢谢!我尝试了上面的代码,但出现错误 ErrorException (E_NOTICE) Undefined index: customerid
  • 你的 csv 文件中是否有标题为 customerid 的列?
  • 很高兴为您提供帮助。你能赞成我的回答吗? :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-03
  • 1970-01-01
  • 2020-10-21
  • 1970-01-01
  • 2013-09-30
  • 2020-11-29
相关资源
最近更新 更多