PHP上传CSV文件时OtherSymptoms空值验证失效问题求助
问题分析与修正方案
核心问题点
- 变量名错误:代码中
$row[$OtherSymptoms]和$row[$OthersSpecify]使用了未定义变量作为数组键,实际应直接使用列名字符串'OtherSymptoms'和'OthersSpecify',否则会导致无法正确获取对应列的值。 - 空值验证逻辑被前置规则拦截:原代码第一个验证规则会将空值判定为无效值(空值不在
['Y','N']范围内),导致后续的空值关联验证(检查OthersSpecify)无法触发。 - 错误消息存在拼写问题:比如
should not value.、sperow这类笔误会降低提示的可读性。
修正后的代码
if ($column === 'OtherSymptoms') { $validValues = ['Y', 'N']; // 修正:使用列名字符串作为数组键 $cellValue = $row['OtherSymptoms']; $othersSpecifyValue = $row['OthersSpecify']; // 修正:仅当单元格不为空时,验证是否为Y/N if (!empty($cellValue) && !in_array($cellValue, $validValues)) { $response['errors'][] = [ 'error' => 'Invalid ' . $column . ' Value', 'message' => '• The value for ' . $column . ' in row ' . $i . ': "' . $cellValue . '" is not valid. Accepted values are: "' . implode('" or "', $validValues) . '".' ]; } // 空值关联验证:OtherSymptoms为空时,OthersSpecify必须为空 if (empty($cellValue) && !empty($othersSpecifyValue)) { $response['errors'][] = [ 'error' => 'Invalid ' . $column . ' Value', 'message' => '• The value for ' . $column . ' is empty in row ' . ($i) . ', therefore ' . 'OthersSpecify' . ' should not have a value.' ]; } // Y值关联验证:OtherSymptoms为Y时,OthersSpecify不能为空 if ($cellValue === 'Y' && empty($othersSpecifyValue)) { $response['errors'][] = [ 'error' => 'Invalid ' . $column . ' Value', 'message' => '• The value for ' . $column . ' is set to Y in row ' . ($i) . ', therefore ' . 'OthersSpecify' . ' in the specified row must not be empty.' ]; } // N值关联验证:OtherSymptoms为N时,OthersSpecify必须为空 if ($cellValue === 'N' && !empty($othersSpecifyValue)) { $response['errors'][] = [ 'error' => 'Invalid ' . $column . ' Value', 'message' => '• The value for ' . $column . ' is set to N in row ' . ($i) . ', therefore ' . 'OthersSpecify' . ' in the specified row must be empty.' ]; } }
关键修改说明
- 将数组键改为明确的列名字符串,确保能正确读取CSV列的值。
- 调整第一个验证规则的触发条件,仅当
$cellValue不为空时才检查是否属于Y/N,避免空值被提前判定为无效,保证后续的空值关联验证正常执行。 - 修正错误消息中的拼写问题,让提示文本更准确通顺。
内容的提问来源于stack exchange,提问作者J0sh
相关产品推荐
相关产品推荐

