我有一个脚本,它使用explode将csv文件导入MySQL表中以分隔字段。我在csv文件中的最后一个字段是日期时间字段,但格式不正确,如下图所示:
我想使用下面的代码将csv插入MySQL并将最后一列的格式从mm / dd / yyyy hh:mm:ss am / pm更改为yyyy-mm-dd的MySQL格式hh: MM:SS
现有的工作脚本(只是不导入日期时间字段,因为格式错误):
$fieldseparator = ",";
$lineseparator = "\n";
$csvfile = "LoadsOverWB.csv";
foreach(split($lineseparator,$csvcontent) as $line) {
$lines++;
$line = trim($line," \t");
$line = str_replace("\r","",$line);
/************************************
This line escapes the special character. remove it if entries are already escaped in the csv file
************************************/
$line = str_replace("'","\'",$line);
/*************************************/
$linearray = explode($fieldseparator,$line);
$linemysql = implode("','",$linearray);
if($addauto)
$query = "replace into $databasetable(loadnumber,weighbillnumber,VehicleRegistration,haulier,vehicleweight,rolledproductkg,hegrosskg,roofinhkg,nonmetalkg,wbtotalkg,datetime) values('','$linemysql');";
else
$query = "replace into $databasetable(loadnumber,weighbillnumber,VehicleRegistration,haulier,vehicleweight,rolledproductkg,hegrosskg,roofinhkg,nonmetalkg,wbtotalkg,datetime) values('$linemysql');";
$queries .= $query . "\n";
@mysql_query($query);
}
一如既往地感谢,非常感谢。
答案 0 :(得分:1)
爆炸后只需添加两行
$key = count($linearray);
$linearray[$key - 1] = date('Y-m-d H:i:s',strtotime($linearray[$key - 1]));
$linemysql = implode("','",$linearray);
在插入print_r之前,还要查看格式是否已更改。
编辑:
查看您正在使用的库我假设每行的最后一个索引是您的日期列(TIME OVER WEB)。所以我算数组的长度和数 - 1给我最后一个索引,所以我应用PHP日期函数。 日期( '格式',的strtotime(DATEVALUE)) strtotime将给定的字符串转换为32431234等数字,然后date函数获取两个参数。格式和数量。我相信这足以让你理解。
答案 1 :(得分:1)
首先,您应该查看fgetcsv()。您将每行都放入一个数组中,并且能够更好地处理它。
要回答你的问题,你需要格式化日期。
$date = $linearray['date']; // or what key your date has
$date = date('Y-M-d H:i:s', strtotime($date));