使用 PHP 无法对上传 csv 文件进行空验证

问题描述 投票:0回答:1

美好的一天,

我试图在我的代码中添加一个验证,如果“OtherSymptoms”列为空并且“OthersSpecify”有值,它将返回一条消息,表明“OthersSpecify”应该为空,因为“OtherSymptoms”为空。

下面是我的代码:

if ($column === 'OtherSymptoms') {
    $validValues = ['Y', 'N'];
    $cellValue = $row[$OtherSymptoms];
    $othersSpecifyValue = $row[$OthersSpecify]; 

    if (!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) . '".'
        ];
    }

    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 value.'
        ];
    }

    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 sperow must not be empty.'
        ];
    }

    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.'
        ];
    }
}

“Y”和“N”验证工作正常,但当列的空行不行时。我将不胜感激纠正和解决方案。谢谢你们。

php csv upload
1个回答
0
投票
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 value.'
    ];
}

您正在测试“OtherSymptoms”($cellValue) 和“OthersSpecify”($othersSpecifyValue) 是否均为空。如果满足此条件,您将添加一条错误消息,这似乎与您想要的相反。如果我理解正确,如果“OtherSymptoms”和“OthersSpecify”均为空,您希望显示错误。当“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 be empty.'
    ];
}
© www.soinside.com 2019 - 2024. All rights reserved.