2014-02-08 52 views
0

我完全摸不着頭腦,其中甚至開始在這一點,但我需要提供關鍵字列表中的文件A,然後在同一名單B.合併兩個文本文件用PHP - foreach循環

有了這些過文件,我想在foreach線上線追加在文件B

例如:

文件:
一號線
2號線
3號線

文件B:
test1的
test2的
TEST3

輸出到combined.txt文件:

line1test1
line2test1
line3test1
line1test2 ...等等

如果您可以提供我要研究的部分腳本,一個示例腳本,甚至是一個工作國王的方式來做到這一點。我將不勝感激。

每請求,這是我的示例代碼:

<?php 

$file1 = 'keywords.txt'; 
$file2 = 'topics.txt'; 
$combined = 'combined.txt'; 

$keywords = fopen("keywords.txt", "rb"); 
$topics = fopen("topics.txt", "rb"); 
$front = explode($topics); 
$back = explode($topics); 

while (!feof($keywords)) { 

file_put_contents($combined, . $front ."". $back . "\n"); 

fclose($keywords & $topics); 
} 
?> 
+1

您需要提供代碼示例以證明您至少已經嘗試過。 – jeremyjjbrown

回答

1

希望這有助於。評論貫穿整個代碼,我希望對我正在做的事情有足夠的解釋。

<?php 

// Open keywords file for reading 
$keywords_file = 'keywords.txt'; 
$keywords_fh = fopen($keywords_file, 'r'); 

// Get line by line from keywords file, push into $keywords array 
// Make sure to trim each line from fgets, to strip off \n at end. 
$keywords = array(); 
while ($line = trim(fgets($keywords_fh))) { 
    array_push($keywords, $line); 
} 
fclose($keywords_fh); 

// Open topics file for reading 
$topics_file = 'topics.txt'; 
$topics_fh = fopen($topics_file, 'r'); 

// Get line by line from topics file, push into $topics array 
// Make sure to trim each line from fgets, to strip off \n at end. 
$topics = array(); 
while ($line = trim(fgets($topics_fh))) { 
    array_push($topics, $line); 
} 
fclose($topics_fh); 

// Open combined file for writing 
$combined_file = 'combined.txt'; 
$combined_fh = fopen($combined_file, 'w'); 

// Iterate through each keyword. 
// For each iteration, iterate through each topic. 
// Write the concatenation of keyword and topic to file. 
foreach ($keywords as $keyword) { 
    foreach ($topics as $topic) { 
    fwrite($combined_fh, "$keyword$topic\n"); 
    } 
} 

fclose($combined_fh); 

這裏有一些鏈接到PHP文件的一些我所用的關鍵功能:

+0

地板非常感謝其他多個單詞。這正是我想要的。也感謝鏈接,有一些學習要做! – CodingNoob

+0

快樂編程和快樂學習! –

1
$f1 = explode("\n",file_get_contents("fileA.txt")); 
$f2 = explode("\n",file_get_contents("fileB.txt")); 
foreach ($f1 as $key => $value) { 
    $f3[] = $value.$f2[$key]; 
} 
file_put_contents("fileC.txt", implode("\n",$f3)); 
+0

這是該結束了輸出: 鳳凰 水暖 檯面 加熱 吉爾伯特 屋面 chandlerflooring 即使我有比FILEB – CodingNoob