查找csv是否有特定的标头,如果有,则格式化该特定值


Find if csv has a specific header and if yes, format that specific value

我已经为这个PHP问题挣扎了一段时间。我有一个csv文件,里面有客户端信息,看起来像这样。

clientName, clientNumber, clientStatus
Name1,123456,1
Name2,123457,0

现在,问题如下。有时csv也有出生日期。。。如下所示:

clientName, clientNumber, clientDOB, clientStatus
Name1,123456,01/10/1980,1
Name2,123457,1980-10-01,0

正如你所看到的,日期有不同的格式。在将csv转换为数组时,我需要检查csv中是否有clientDOB,如果有,则将其格式化为mysql。

function dateToMysql($date) {
    $mysqlDate = date("Y-m-d",strtotime(str_replace('/','-',$date)));
    return $mysqlDate;
}
function csvToArray($filename='', $delimiter=',') {
    if(!file_exists($filename) || !is_readable($filename)) {
        return FALSE;
    }
    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
            if(!$header) {
                $header = $row;
            } else {
                if (in_array("clientDOB", $header)) {
                    //echo dateToMysql($header['clientDOB'][$row])."<br>";
                    $data[] = dateToMysql(array_combine($header, $row));
                } else {
                    $data[] = array_combine($header, $row);
                }
            }
        }
        fclose($handle);
    }
    return $data;
}
echo "<pre>";
print_r(csvToArray($_FILES['csvFile']['name']));
echo "</pre>";

如有任何帮助,我们将不胜感激。感谢

这里有一个更新的函数:

function csvToArray($filename='', $delimiter=',') {
    if(!file_exists($filename) || !is_readable($filename)) {
        return FALSE;
    }
    $header = NULL;
    $data = array();
    if (($handle = fopen($filename, 'r')) !== FALSE) {
        while (($row = fgetcsv($handle, 10000, $delimiter)) !== FALSE) {
            $row = array_map('trim', $row);
            if (!$header)
                $header = $row;
            else
            {
              $row = array_combine($header, $row);
              if ( isset( $row[ 'clientDOB' ] ) )
                  $row[ 'clientDOB' ] = date('Y-m-d', strtotime( $row[ 'clientDOB' ] ) );
              $data[] = $row;
            }
        }
        fclose($handle);
    }
    return $data;
}

显著变化:

  • $row = array_map('trim', $row)确保名称和值周围没有空格,否则['clientDOB']将不匹配(因为它是[' clientDOB'].

  • 在将CCD_ 5附加到CCD_ 6之前改变CCD_。dateToMysql函数需要一个$date,但实际传递给它的却是一个关联数组。

  • 使用strtotime不需要替换:它可以处理两种日期格式。