用于将Maatwebsite
Excel 文件上传到数据库。
每行都有一个属性类型,例如“阁楼”或“别墅”。
我想收集每一行的每种属性类型。
使用以下功能将不起作用:
Excel::filter('chunk')->load($csv->getRealPath())->chunk(250, function ($results) {
DB::table('prices')->truncate();
foreach ($results as $row) {
/**
* @var CellCollection $row
*/
array_push($this->property_types, $row->property_type);
$price = Price::create($row->all());
}
});
$this->property_types
在函数中定义__construct
如下:
public function __construct()
{
$this->middleware('auth');
$this->property_types = [];
}
这将导致一个空数组。
如此处所述,定义数组和using
& 符号可能会解决问题,尽管这将返回相同的结果,即一个空数组。
$data = [];
Excel::filter('chunk')->load($csv->getRealPath())->chunk(250, function ($results) use (&$data) {
DB::table('prices')->truncate();
foreach ($results as $row) {
/**
* @var CellCollection $row
*/
array_push($data, $row->property_type);
$price = Price::create($row->all());
}
});
我必须做什么才能在匿名函数内定义数据,并在函数外检索数据?