Доступ к переменной вне Excel :: load in Laravel -excel - PullRequest
1 голос
/ 08 мая 2020

Я пытаюсь передать переменную в функцию ниже. Я попробовал глобальную переменную и по ссылке, но счетчики продолжают сбрасываться (как показано во втором фрагменте кода).

private $counter = 0;

 public function importExcel(Request $request)
 {
   $count = 0
    **some other code**
                try {
                    Excel::filter('chunk')->load($path)->chunk(1000, function($reader) use($tableName, $tableColumns, &$count) {
                        var_dump($this->counter);
                        var_dump($count);
                        if ($reader->count() && ($this->counter < 30 || $count < 30)) {
                        $this->counter++;
                        $count++;
                        var_dump('inside: ' . $this->counter . ';' . $count);
                            /** Get uploaded file columns **/
                            $headerRow = $reader->first()->keys()->toArray();

                            /** Check if destination table columns are found in uploaded file **/
                            if (is_array($headerRow) && !array_diff($tableColumns, $headerRow)) {
                                /** Extract only the data we need in destination table from uploaded file **/
                                $data = array_map(function($row) use($tableColumns) {
                                    $arr = [];
                                    foreach ($tableColumns as $column) {
                                        $arr[$column] = $row[$column];
                                    }
                                    return $arr;
                                }, $reader->toArray());

                                /** Insert the data we need to destination table **/
                                DB::connection(*censored*)
                                    ->table($tableName)
                                    ->insert($data);
                            }
                        }
                    });
 }

результаты:

int(0)
int(0)
string(11) "inside: 1;1"
int(0)
int(0)
string(11) "inside: 1;1"
int(0)
int(0)
string(11) "inside: 1;1"
int(0)
int(0)
string(11) "inside: 1;1"
int(0)
int(0)
string(11) "inside: 1;1"
etc... etc... etc...

Почему оба счетчика не накапливаются? Как мне заставить счетчики накапливаться? исправления или другие решения приветствуются.

...