You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP上传CSV文件时OtherSymptoms空值验证失效问题求助

问题分析与修正方案

核心问题点

  1. 变量名错误:代码中$row[$OtherSymptoms]和$row[$OthersSpecify]使用了未定义变量作为数组键,实际应直接使用列名字符串'OtherSymptoms'和'OthersSpecify',否则会导致无法正确获取对应列的值。
  2. 空值验证逻辑被前置规则拦截:原代码第一个验证规则会将空值判定为无效值(空值不在['Y','N']范围内),导致后续的空值关联验证(检查OthersSpecify)无法触发。
  3. 错误消息存在拼写问题:比如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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.06 00:00:28