将Excel转换为Laravel中的数组 [英] Convert excel to array in Laravel

查看:505
本文介绍了将Excel转换为Laravel中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matlab excel插件将excel转换为数组.我的代码是:-

I'm using matlab excel plugin for convert excel to array. My code is:-

public static function ImportExcel($table="", $path=""){
    $data = array();
    Excel::load($path, function ($reader) use($data) {
        $data = $reader->toArray();
        //here data has all excel data in array.
    });
    return $data; //but here it shows empty array.
}

检查我在代码中的注释.在Excel :: load数据内部具有所有数据的数组.但是它的作用域仅在Excel :: load中.我在外面需要它.

Check my comments in code. Inside the Excel::load data has array of all data. But its scope is only inside the Excel::load. I need it outside.

推荐答案

加载具有内部函数,因此变量被封装在该函数内部,并且除非将其传递给函数,否则它也无法从该函数外部访问变量用use语句.换句话说,函数内部的$ data不引用函数外部的$ data.为了解决这个问题,您必须像这样将$data添加到use语句中:

The load has an internal function, thus the variables are enclosed inside that function and it also cannot access variables from outside this function, unless they are passed to the function with the use statement. In other words, $data inside the function does not reference to the $data outside it. In order to fix this you will have to add $data to the use statement like this:

public static function ImportExcel($table="", $path=""){
    $data = array();
    Excel::load($path, function ($reader) use($table, $data) {
        $data = $reader->toArray();
        //here data has all excel data in array.
    });
    return $data; //but here it shows empty array.
}

这篇关于将Excel转换为Laravel中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆