2011-02-06 209 views
0

我有兩個文本文件,並通過這兩個文件要環路,則結合了線(第一測試文件和第二個文本文件的第1行的1號線,這樣對千行),並做一些功能如何循環兩個文件併合並相同的文件?

我熟悉通過一個文件和代碼迴路如下:

$lines = file('data.txt'); 
foreach ($lines as $line) { 

//some function 


} 

但如何將兩個文件執行,並結合博特線?

+0

你是什麼意思的「搜索表」?您想要尋找什麼? – 2011-02-06 18:45:54

+0

表示將兩個文件中的某些數據逐行結合在一起,然後搜索table1並將結果存儲到table2。 – limo 2011-02-06 18:49:35

回答

1

不知道你通過表搜索是什麼意思到任何分隔符來調整的fread讀取的字節數,但打開這兩個文件,做的東西與他們:

$file1 = fopen("/path/to/file1.txt","r"); //Open file with read only access 
$file2 = fopen("/path/to/file2.txt","r"); 
$combined = fopen("/path/to/combined.txt","w"); //in case you want to write the combined lines to a new file 

while(!feof($file1) && !feof($file2)) 
{ 
    $line1 = trim(fgets($file1)); //Grab a line of the first file, note the trim will clip off the carriage return/new line at the end of the line, can remove it if you don't need it. 
    $line2 = trim(fgets($file2)); //Grab a line of the second file 

    $combline = $line1 . $line2; 

    fwrite($combined,$combline . "\r\n"); //Write to new combined file, and add a new carriage return/newline at the end of the combined line to replace the one trimmed off. 

    //You can do whatever with data from $line1, $line2, or the combined $combline after getting them. 
} 

注意:您可能會遇到麻煩,如果你打一個文件,文件結束前對方,如果他們是不一樣的長度,因爲這隻會發生,可能需要一些if語句來將$ line1或$ line2設置爲""或別的東西,如果feof()其各自的文件,一旦兩個命中文件的結尾,while循環將結束。

0

例子:

$file1 = fopen("file1.txt", "rb"); 
$file2 = fopen("file2.txt", "rb"); 

while (!feof($file1)) { 
    $combined = fread($file1, 8192) . " " . fread($file2, 8192); 
    // now insert $combined into db 
} 
fclose($file1); 
fclose($file2); 
  • 你將要使用的兩個文件中較長的,而條件。
  • 你可能需要根據你的線條有多長
  • 變「」你想
0

您可以按照蠟筆和蒂姆所示的方式編程。如果兩個文件具有相同的行數,它應該工作。如果行號不同,您將不得不遍歷較大的文件以確保您獲得所有行或檢查EOF。

要逐行組合,我經常使用非常快的unix命令粘貼。這也解釋了不同長度的文件。在命令行中運行以下命令:

paste file1 file2 > output.txt 

manpagepaste的命令行選項,字段分隔符。

man paste