Laravel Excel:CSV到数组

所以我正在做一个表单,我想要给用户上传一个CSV的选项,这个表单可以被自动填充。 所以我想我会构build一个读取CSV的函数,然后把每一行都作为一个对象传递给一个数组,然后我可以传回到我的Laravel Blade模板。 我唯一的问题是,我从函数返回的数组总是空的。 有任何想法吗?

private function import($path) { $applicants = []; Excel::load($path, function(LaravelExcelReader $excel) use ($applicants){ $excel->each(function(Collection $line) use ($applicants){ $name = new \stdClass; $name->first = $line->get('first'); $name->middle = $line->get('middle'); $name->last = $line->get('last'); $name->birthdate = $line->get('birthdate'); $name->ssn = $line->get('ssn'); $name->email = $line->get('email'); $name->mobile_phone = $line->get('mobile_phone'); $name->home_phone = $line->get('home_phone'); $name->street = $line->get('street'); $name->city = $line->get('city'); $name->state = $line->get('state'); $name->zip = $line->get('zip'); array_push($applicants, $name); }); }); return $applicants; } 

use语句中使用&运算符来尝试:

 Excel::load($path, function(LaravelExcelReader $excel) use (&$applicants){ ... } 

要么

使$applicants人类属性然后在您的函数中使用它:

 private function import($path) { $this->applicants = []; Excel::load($path, function(LaravelExcelReader $excel) { $excel->each(function(Collection $line) { ... array_push($this->applicants, $name); }); }); return $this->applicants; } 

安装 – https://github.com/Maatwebsite/Laravel-Excel

然后尝试下面的代码:

 $reader = \Excel::load($file_path); //this will load file $results = $reader->noHeading()->get()->toArray(); //this will convert file to array foreach($results as $v){ \\process your array } 

代替

 array_push($applicants, $name); 

尝试这个

 $applicants[] = $name; 

让我知道如果它的作品