数组为空,不显示任何内容

Array is empty, shows nothing

我尝试 dd($inserts) 但它显示“[]”。这是我控制器中的代码。

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();
}

因为您似乎有 "rows" 而不是只有 "row",您需要再次遍历这些行。

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']];
        }
    }    
});

实际上你可以这样做。

$rows = $reader->toArray();

foreach($rows as $row) { // <-- $row pertains to the row itself
    $inserts[] = ['title' => $row['title'], 'description' => $row['description']];
}

或者如果你想坚持使用 get,我认为 returns 一个集合。

$rows = $reader->get();

foreach($rows as $row) {
    $inserts[] = ['title' => $row->title, 'description' => $row->description];
}

更新

为了反映$inserts数组的修改,需要传递它的引用。

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