2012-04-11 39 views
1

我有zip文件,我得到的是,解壓縮時,有幾個子文件夾每個都包含了一個名爲report.csv CSV:使用UNIX和PHP獲得子文件夾的名稱,以投入爲.csv

the_folder/ 
    1234/report.csv 
    abcd/report.csv 
    jklm/report.csv 
    5678/report.csv 

每個CSV的有列&內容,如:

almonds, biscuits, cookies, dog_biscuits 
123, 321, 333, 444 
555, 666, 777, 888 
444, 551, 555, 999 (and so on for 75 lines or so) 

我希望把自己變成一個組合CSV文件。我一直使用EXEC在一個PHP文件來做到這一點:

exec("cat /path/the_folder/*/report.csv > /path/combined.csv"); 

,然後用sed來刪除重複的「杏仁,餅乾,曲奇,dog_biscuits」標題行。

現在我需要把子文件夾的名稱,並把它們放到combined.csv的行。

因此,會在CSV(「subfolder_name」)中添加一列,然後在該列中顯示該行所來自的文件夾的名稱。類似於

almonds, biscuits, cookies, dog_biscuits, subfolder_name 
123, 321, 333, 444, 1234 
555, 666, 777, 888, 1234 
444, 551, 555, 999, abcd 
333, 333, 111, 222, abcd 
111, 222, 444, 333, abcd (etc and so on for 300 lines) 

什麼是最簡單,最有效率的方法?

回答

0

您可以嘗試

$folderList = array (
     "1234/report.csv", 
     "abcd/report.csv", 
     "jklm/report.csv", 
     "5678/report.csv" 
); 

$combinedCSV = "result_combine.csv"; 
$headers = array (
     "almonds", 
     "biscuits", 
     "cookies", 
     "dog_biscuits" 
); 
touch ($combinedCSV); 

$fp = fopen ($combinedCSV, 'w'); 
fputcsv ($fp, $headers); // Add headers 
foreach ($folderList as $file) { 
    if (($handle = fopen ($file, "r")) !== FALSE) { 
     while (($data = fgetcsv ($handle, 1000, ",")) !== FALSE) { 
      if ($data [0] == "almonds") // Remove Headers 
       continue; 
      fputcsv ($fp, $data); 
     } 
     fclose ($handle); 
    } 
} 

fclose($fp); 

我希望它能幫助

感謝

+0

對不起,我已經把它給了其他人!謝謝你。 – 2012-04-12 00:23:21

+0

它確定你是受歡迎的..//確保你刪除多個標題..因爲它們都包含在所有文件中 – Baba 2012-04-12 00:24:33

0

試試這個:

$folder_list = array(); // USE YOUR CODE TO GET FOLDER LIST 
$combined_output = ""; 
$folder_i = 0; 
foreach ($folder_list as $folder) { 
    $file = file($folder . "/report.csv"); 
    foreach ($file as $line_i => $line) { 
     if (($folder_i == 0 && $line_i == 0) || $line_i > 0) { 
     $combined_output .= $line . PHP_EOL; 
     } 
    } 
    $folder_i++; 
} 

$f = fopen("combined.csv", "w+"); 
fwrite($f, $combined_output); 
fclose($f); 
+0

啊塔完全有道理謝謝!它甚至不需要使用所有的「exec」。非常感謝。 – 2012-04-12 00:17:16

0

TXR:

@header 
@(output) 
@header, subfolder_name 
@(end) 
@(next :args) 
@(collect) 
@folder/@subfolder/@file.csv 
@ (next `@folder/@subfolder/@file.csv`) 
@header 
@ (collect :vars()) 
@line 
@ (output) 
@line, @subfolder 
@ (end) 
@ (end) 
@(end) 

運行:

$ txr catname.txr folder/*/*.csv 
animal, sound, subfolder_name 
dog, bark, abcd 
horse, neigh, abcd 
cat, meow, efgh 
cow, moo, efgh 

數據:

$ ls -R folder/ 
folder/: 
abcd efgh 

folder/abcd: 
a.csv 

folder/efgh: 
e.csv 

$ cat folder/abcd/a.csv 
animal, sound 
dog, bark 
horse, neigh 

$ cat folder/efgh/e.csv 
animal, sound 
cat, meow 
cow, moo 
相關問題