php - Laravel Excel : CSV to Array

标签 php arrays excel laravel csv

因此,我正在制作一个表单,我希望为用户提供上传 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/

相关文章:

php - 使用 .htaccess 将不带扩展名的热链接重定向到父网站

java - 使用 for 循环用两个一维数组填充二维数组

sql - 使用Excel生成SQL——问题处理日期字段

python - 如何检测 Excel 工作表中的合并单元格?

vba - 定义两个范围,然后将它们连接起来

javascript - 如何创建自定义交易 ID php

php - 如何使用CSS水平对齐

javascript - 过滤数组并创建新数组

arrays - 1D 索引的 4D 位置?

php - MySQL更新记录,但页面显示不显示新数据