1

我有一个 zip 文件,当我解压缩时,有几个子文件夹,每个子文件夹都包含一个名为 report.csv 的 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 文件中。我一直在 PHP 文件中使用 exec 来执行此操作:

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

然后使用 sed 删除重复的“almonds, biscuits, cookies, 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)

最聪明、最简单、最有效的方法是什么?

4

3 回答 3

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);
于 2012-04-12T00:06:22.440 回答
0

发射器:

@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
于 2012-04-13T17:19:37.500 回答
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);

我希望它有帮助

谢谢

于 2012-04-12T00:21:19.743 回答