当前正在做一个需要我将CSV文件中的数据导入数据库的项目,这是文件的数据示例:
| id_attendance | name | date | time |
-----------------------------------------------------
| 001 | lily |01.01.2018| 07:00 |
| 002 | thomas |01.01.2018| 07:02 |
| 003 | lily |01.01.2018| 19:00 |
| 004 | thomas |01.01.2018| 19:02 |
-----------------------------------------------------
与此同时,我需要将这些数据导入此类表
| id_attendance | name | date | time_in | time_out |
--------------------------------------------------------------------
| 001 | lily |01.01.2018| 07:00 | 19.00 |
| 002 | thomas |01.01.2018| 07:02 | 19.02 |
--------------------------------------------------------------------
这需要我自动将时间字段分为time_in和time_out。到目前为止,我已经完成了csv导入,这是我的代码
importcsv_m.php 模型
function importCSV()
{
$count=0;
$fp = fopen($_FILES['userfile']['tmp_name'],'r') or die("can't open file");
while($csv_line = fgetcsv($fp,1024))
{
$count++;
if($count == 1)
{
continue;
}
for($i = 0, $j = count($csv_line); $i < $j; $i++)
{
$insert_csv = array();
$insert_csv['id_attendance'] = $csv_line[0];
$insert_csv['name'] = $csv_line[1];
$insert_csv['date'] = $csv_line[2];
$insert_csv['time'] = $csv_line[3];
}
$i++;
$data = array(
'id_attendance' => $insert_csv['id_attendance'] ,
'name' => $insert_csv['name'],
'date' => $insert_csv['date'],
'time' => $insert_csv['time'],
);
$data['crane_features']=$this->db->insert('attendance', $data);
}
fclose($fp) or die("can't close file");
$data['success']="success";
}
但是它仅导入数据而不会分隔时间(没有time_in和time_out)
我想知道我是否可以导入一个数组并将其分为两个?
答案 0 :(得分:0)
我创建了一些代码,试图匹配每个班次的开始和结束。这是通过查找匹配的开始记录,然后为结束时间添加数据来实现的。如果找不到匹配的起始记录,则它将存储此数据(假设这是起始记录)。找到结束记录后,开始记录将从$attendancies
中删除,因为下一条记录可能是新的班次...
function importCSV()
{
$fp = fopen($_FILES['userfile']['tmp_name'],'r') or die("can't open file");
// Ignore header line
$header = fgetcsv($fp);
// Array to store the partial records
$attendancies = [];
while($csv_line = fgetcsv($fp))
{
// Key to identify first part of record (Name and date)
$key = $csv_line[1]."/".$csv_line[2];
if ( isset($attendancies[$key]) ){
$start = $attendancies[$key];
// Extract data from first part of record and add in end date from current row
$data = array(
'id_attendance' => $start[0] ,
'name' => $start[1],
'date' => $start[2],
'time_in' => $start[3],
'time_out' => $csv_line[3],
);
$data['crane_features']=$this->db->insert('attendance', $data);
// Remove partial record
unset($attendancies[$key]);
}
else {
// Store partial record
$attendancies[$key] = $csv_line;
}
}
fclose($fp) or die("can't close file");
$data['success']="success";
}