我想询问当我在Excel :: load函数中执行foreach循环时如何访问错误消息变量,该函数读取我上传的csv文件,以便我可以通过Response :: JSON();
这是我的代码:
$errorMessage['error'] = [];
if($request->hasFile('file')){
if($request->file('file')->getClientOriginalExtension() != "csv"){
$errorMessage['error'][] = "File should be in csv format";
}
else {
$fileName = $request->file('file')->getClientOriginalName().".csv";
$destination = base_path().'/storage/excel/imports';
$request->file('file')->move($destination, $fileName);
$csvFile = base_path().'/storage/excel/imports/'.$fileName;
$demographics = $request->get('demographics');
\Excel::load($csvFile, function($reader) use($demographics,$errorMessage) {
if($demographics == "region"){
foreach($reader->get()->toArray() as $data){
$region = Region::whereRaw("LCASE(`short_name`) = ?", array(strtolower($data['region_name'])))->first();
if($region){
$regionData = Region::find($region->id);
$regionData->total_number_of_provinces = $data['total_provinces'];
$regionData->total_number_of_cities_municipalities = $data['total_cities_and_municipalities'];
$regionData->save();
}
else {
$errorMessage['error'][] = $data['region_name'] . " is not existing in the database";
}
}
}
});
}
}
else {
$errorMessage['error'][] = "Please specify a file";
}
return \Response::json($errorMessage);
答案 0 :(得分:1)
有点臭,但你可以声明它是一个类属性。
/**
* @var array
*/
protected $errorMessage;
public function doStuff()
{
// ...
\Excel::load($file, function($reader) use ($demographics) {
// ...
$this->errormessage['error'][] = $data['region_name'];
});
// ...
return \Response::json($this->errorMessage);
}
注意强>
您也可以通过引用传递$errorMessage
,很多人认为这是更好的选择(毕竟你使用的是丢弃功能)。
\Excel::load($file, function($reader) use ($demographics, &$errorMessage)
我不喜欢这样做,因为在我看来,我的意思不太可读。你可以选择其中一个选择!
有用且简短的解释:http://culttt.com/2013/03/25/what-are-php-lambdas-and-closures/
答案 1 :(得分:0)
$fileName = md5(time()) .'.'.$request->file('file')->getClientOriginalExtension();
$sheet_id = $request->session()->get('sheet_id');
$excel=Excel::load(public_path('/uploads/importsheet/'.$fileName),function ($reader)use ($sheet_id) {
$reader->each(function($sheet) use ($sheet_id) {
$headings = $sheet->keys()->toArray();
for($i=0; $i<count($headings); $i++){
$sheet_id = DB::table('import_sheets_attributes')->insertGetId(
[
'import_sheets_id' => $sheet_id,
'attribute' => $headings[$i],
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s')
]);
}
});
});
希望上面的示例代码会有所帮助。