因此,我正在制作一个表单,我希望为用户提供上传 CSV 的选项,以便自动填充表单。所以我想我应该构建一个函数来读取 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;
}
关于php - Laravel Excel : CSV to Array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41169295/