获取 Laravel 中 sheet 的总数

Get total number of sheet in Laravel

我正在尝试获取 Laravel 中上传的 Excel 文件中的总页数。我上传的文件有 3 张。所以我期望得到 $counter = 3.

的输出

代码:

$counter=0;
Excel::load($fileDetails['file_path'], function($sheet) use($counter) {
    $sheet->each(function($sheet) use($counter) {
        echo "It works</br>";   
        $counter++;
    });
});
echo $counter; exit;

输出:

It works
It works
It works
0   //-- This is $counter, which is not get incremented. It has to be 3.

use 的工作方式类似于传递参数。默认是按值传递,所以在函数内部所做的任何修改都不会反映在函数范围之外。

但是,如果您通过引用传递变量,则会反映更改。

将您的代码更新为:

$counter=0;
// add & to have var passed by reference
Excel::load($fileDetails['file_path'], function($sheet) use(&$counter) {
    // add & to have var passed by reference
    $sheet->each(function($sheet) use(&$counter) {
        echo "It works</br>"; 
        $counter++;
    });
});
echo $counter;
exit;