我是一名爲夏季工作的學生。我已經被賦予處理從excel到SQL Server數據庫的數據輸入的任務,以進行多年的調查。任務如下:我是否正在處理這些文件? (帶PHP的CSV)
有三個表,一個主要事件,一個個別事件和一個個人。一個事件有許多個人事件,一個事件有許多個人事件。我的代碼只關注最後兩個表。
我讀了兩個文件,一個文件中的所有單個事件的列表,以及另一個文件中的所有個人的列表。個人的數據告訴我它與哪個單獨的事件相關聯。
我的代碼基本上讀取一個單獨的事件,然後通過第二個文件查找任何關聯的個人。對於個人文件中的每一行,如果它是關聯的,則將其插入到適當的表中,否則將被寫入新文件。遍歷完整個文件後,新文件將被複制到舊文件中,從而刪除已輸入數據庫的數據。
這個複製過程已經敲了好3分鐘的執行時間,只需重新讀取完整的個人文件即可。但有沒有更好的方法呢?我的樣本數據的執行時間爲〜47秒...理想情況下,我希望更低。
任何意見,無論多麼微不足道的讚賞。
編輯: 這是代碼的削減版本,我使用
<?php
//not shown:
//connect to database
//input event data
//get the id of the event
//open files
$s_handle = fopen($_FILES['surveyfile']['tmp_name'],'r');//open survey file
copy($_FILES['cocklefile']['tmp_name'],'file1.csv');//make copy of the cockle file
//read files
$s_csv = fgetcsv($s_handle,'0',',');
//read lines and print lines
// then input data via sql
while (! feof($s_handle))
{
$max_index = count($s_csv);
$s_csv[$max_index]='';
foreach($s_csv as $val)
{
if(!isset($val))
$val = '';
}
$grid_no = $s_csv[0];
$sub_loc = $s_csv[1];
/*
.define more variables
.*/
$sql = "INSERT INTO indipendant_event"
."(parent_id,grid_number,sub_location,....)"
."VALUES ("
."'{$event_id}',"
."'{$grid_no}',"
//...
.");";
if (!odbc_exec($con,$sql))
{
echo "WARNING: SQL INSERT INTO fssbur.cockle_quadrat FAILED. PHP.";
}
//get ID
$sql = "SELECT MAX(ind_event_id)"
."FROM independant_event";
$return = odbc_exec($con,$sql);
$ind_event_id = odbc_result($return, 1);
//insert individuals
$c_2 = fopen('file2.csv','w');//create file c_2 to write to
$c_1 = fopen('file1.csv','r');//open the data to read
$c_csv = fgetcsv($c_1,'0',',');//get the first line of data
while(! feof($c_1))
{
for($i=0;$i<9;$i++)//make sure theres a value in each column
{
if(!isset($c_csv[$i]))
$c_csv[$i] = '';
}
//give values meaningful names
$stat_no = $c_csv[0];
$sample_method = $c_csv[1];
//....
//check whether the current line corresponds to the current station
if (strcmp(strtolower($stat_no),strtolower($grid_no))==0)
{
$sql = "INSERT INTO fssbur2.cockle"
."(parent_id,sampling_method,shell_height,shell_width,age,weight,alive,discarded,damage)"
."VALUES("
."'{$ind_event_id}',"
."'{$sample_method}',"
//...
."'{$damage}');";
//write data if it corresponds
if (!odbc_exec($con,$sql))
{
echo "WARNING: SQL INSERT INTO fssbur.cockle FAILED. PHP.";
}
$c_csv = fgetcsv($c_1,'0',',');
}
else//no correspondance
{
fputcsv($c_2,$c_csv);//write line to the new file
$c_csv = fgetcsv($c_1,'0',',');//get new line
continue;//rinse and repeat
}
}//end while, now gone through all individuals, and filled c_2 with the unused data
fclose($c_1);//close files
fclose($c_2);
copy('file2.csv','file1.csv');//copy new file to old, removing used data
$s_csv = fgetcsv($s_handle,'0',',');
}//end while
//close file
fclose($s_handle);
?>
請顯示一些代碼。你有沒有嘗試過什麼來改進這個過程?你有沒有使用分析器來衡量執行時間? – Gordon
@戈登我避免發佈代碼,因爲它很長。我只是用microtime()來看看它花了多長時間。我會盡快發佈一些代碼 – Aido
上傳的代碼。感謝迄今爲止的答案! – Aido