当前正在执行一个项目,该项目需要我将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";
}
但它只导入数据而不分离时间(没有时间输入和时间输出(
我想知道是否可以导入一个数组并将其一分为二?
我创建了一些代码,试图匹配每个班次的开始和结束。这是通过查找匹配的开始记录,然后添加结束时间的数据来实现的。如果没有找到匹配的开始记录,则它会存储此数据(假设这是开始记录(。一旦找到结束记录,就从$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";
}