我需要循环$request->hasFile()
函数作为更新模块的一部分;
foreach ($answers as $a) {
$ansid = 0;
$ansid = $a['id'];
$ans['quiz_content'] = $data['quiz_content_'.$a['id']];
$ans['quiz_is_answer'] = 0;
if ($data['radio-group8'] == "radio-group8_".$a['id']) {
$ans['quiz_is_answer'] = 1;
}
if ($request->hasFile('quiz_img_'.$ansid) && $data['quiz_content_'.$ansid] == null && !empty($data['quiz_img_'.$ansid])) {
$project_image = $request->file('quiz_img_'.$ansid);
$filename = $ansid.'answer'.time().'.'.$project_image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/elearning/answers');
$project_image->move($destinationPath, $filename);
$ans['quiz_image_name'] = $filename;
$ans['quiz_content_type'] = 2;
} elseif ($request->hasFile('quiz_img_'.$ansid) && $data['quiz_content_'.$ansid] != null && !empty($data['quiz_img_'.$ansid])) {
$project_image = $request->file('quiz_img_'.$ansid);
$filename = $ansid.'answer'.time().'.'.$project_image->getClientOriginalExtension();
$destinationPath = public_path('/uploads/elearning/answers');
$project_image->move($destinationPath, $filename);
$ans['quiz_content'] = $data['quiz_content_'.$ansid];
$ans['quiz_image_name'] = $filename;
$ans['quiz_content_type'] = 3;
}
QuizOption::where('id', $ansid)->update($ans);
}
但是,当我更新测验选项时,说我有三个选项,a,b和c。如果将图像设置在a上,则b和c将获得相同的图像和相同的内容类型。如果将图像设置在b上,则c将获得与b相同的图像和内容类型。我知道问题在于if($request->hasFile())
条件。但是如何编码,以便每个选项a,b和c都有唯一的答案和图片?
答案 0 :(得分:2)
您遇到的问题实际上与您如何在循环中设置$ans
变量有关,而不是与$request->hasFile()
调用有关。因为您永远不会在$ans
内部重设数据-只设置某些索引-在将来的循环中不匹配的条件期间设置的任何数据都不会改变。
以下是问题的简化示例(view result on 3v4l.org):
$data = array();
for ($i = 0; $i < 5; $i++) {
$data['id'] = $i;
if ($i === 2) {
$data['foobar'] = $i;
}
var_dump($data);
}
当if
通过$i = 2
条件时,它将在数组上设置foobar
索引。将来的循环都不会更改该索引或重置$data
数组。
我建议将$ans = [];
或类似的重置放在循环的顶部,以便每个人都获得仅与答案有关的新数据。