无法将excel导入数据库,数组没有任何价值

时间:2018-03-21 03:40:18

标签: laravel laravel-5 laravel-5.5 maatwebsite-excel

我试图将我的excel导入我的数据库,但问题是我的插入数组中没有任何内容。当我尝试dd($ inserts)时,它只显示我 " []&#34 ;.

public function importExcel()
{
    $path = Input::file('import_file')->getRealPath();
    $inserts = [];
    Excel::load($path, function($reader) use ($inserts) {
        foreach ($reader->toArray() as $rows) { // <-- $rows pertains to array of rows
            foreach($rows as $row) { // <-- $row pertains to the row itself
                $inserts[] = ['title' => $row['title'], 'description' => $row['description']];
            }
        }    
    });
    dd($inserts);
    return back();
}

2 个答案:

答案 0 :(得分:0)

我在上一个问题中已经有了这方面的答案,您正在修改$inserts数组,但它只是该闭包内的局部变量,您需要提供一个如果你想修改它,请引用它,只需将你的闭包签名更新为。

function($reader) use (&$inserts)
//                     ^-- add this to use its reference.

因此,当您在闭包内修改它时,它现在将反映在闭包之外。

答案 1 :(得分:0)

另一种做同样事情的方法:

  

如果定义了构造函数,则在构造函数之前定义私有变量。

Class Test { //class name;
    private $inserts;//define after class name

    public function importExcel()
    {
    $path = Input::file('import_file')->getRealPath();
    Excel::load($path, function($reader) {
    foreach ($reader->toArray() as $rows) { 
       foreach($rows as $row) { 
            $this->inserts[] = ['title' => $row['title'], 'description' => $row['description']];
        }
    }    
    });
dd($this->inserts);

}