尝试合并两个csv文件,但仅显示前两行

时间:2019-05-09 09:10:01

标签: php arrays csv foreach import-csv

我正在尝试合并两个csv文件,其中第一个csv占用一个字段,第二个csv占用一个字段,但是当我这样做时,它仅返回第二个文件的第一行/第二行。

if ($ext1 == 'csv' && $ext2 == 'csv') {
            $path1 = ROOT . "/uploads/" . md5(uniqid()) . ".csv";
                $path2 = ROOT . "/uploads/" . md5(uniqid()) . ".csv";
                $file1 = $_FILES['upload']['tmp_name'];
                $file2 = $_FILES['upload2']['tmp_name'];

                move_uploaded_file($file1, $path1);
                move_uploaded_file($file2, $path2);

                $file1 = fopen($path1, 'r');
                $file2 = fopen($path2, 'r');

                if (file_exists($path1) && file_exists($path2)) {
                    header('Content-Type: text/csv');
                    header('Content-Disposition: attachment; filename="sample.csv"');

                    $output_name = md5(uniqid()) . ".csv";
                    $output = ROOT . "/uploads/output/" . $output_name;
                    $fp = fopen($output, 'wb');
                    fputcsv($fp, array('campaign', 'spent', 'payout', 'profit', 'roi'), ',');
                    $found_campaigns = [];

                    fgetcsv($file1); // Skip first line
                    while (($data = fgetcsv($file1)) !== FALSE) {
                        array_push($found_campaigns, $data[$campaign]);
                        echo "<pre>";
                        var_dump($found_campaigns); //  Showing the found campgains
                        echo "</pre>";
                        echo "</br>";


                        // Check if the second file have same campgain name with the first file campgain name if yes take the payout field and merge them with the spent field.
// This returning only the data of the two first lines only ( Need to return all the equal fields )
                        $found_in_file_2 = false;
                        $pout = '';
                        while (($data2 = fgetcsv($file2)) !== FALSE && !$found_in_file_2) {
                            var_dump($data2); // Show the fields of the second file if the campgain name are equal to the first file campaign name
                            if ($data2[$campaign2] == $data[$campaign]) {
                                $found_in_file_2 = true;
                                $pout = $data2[$payout];
                            }
                        }

                        $pout = str_replace('$', '', $pout);

                        $line = [
                            $data[$campaign],
                            $data[$spent],
                            $pout,
                            $pout - $data[$spent],
                            ($pout - $data[$spent]) / $data[$spent]
                        ];

                        fputcsv($fp, $line, ',');
                    }

                    $file1 = fopen($path1, 'r');
                    $file2 = fopen($path2, 'r');
                    fgetcsv($file2); // Skip first line
                    while (($data = fgetcsv($file2)) !== FALSE) {
                        if (!in_array($data[$campaign2], $found_campaigns)) {
                            $found_in_file_1 = false;
                            $spt = '';
                            while (($data2 = fgetcsv($file1)) !== FALSE && !$found_in_file_1) {
                                if ($data2[$campaign] == $data[$campaign2]) {
                                    echo $data2[$campaign] . ' ' . $data[$campaign2] . '<br>';
                                    $found_in_file_1 = true;
                                    $spt = $data2[$spent];
                                }
                            }

                            $spt = str_replace('$', '', $spt);
                            $pout = $data[$payout];
                            $pout = str_replace('$', '', $pout);

                            if ($spt > 0) {
                                $roi = ($pout - $spt) / $spt;
                            } else {
                                $roi = 0;
                            }

                            $line = [
                                $data[$campaign2],
                                $spt,
                                $pout,
                                $pout - $spt,
                                $roi
                            ];

                            fputcsv($fp, $line, ',');
                        }
                    }

                    fclose($fp);
                    $now = date("d_m_Y H:i",time());
                    echo '<a class="btn btn-primary" href="uploads/output/' . $output_name . '" download="'. $now .'.csv">Download Merged File</a>';
                }
            } 

文件内容

第一个文件(需要花点时间才能工作):

Campaign ID Campaign Name   Impressions Rate    Cost
4833222 ZroJumiaNGMob1  15335   0.00014 2.1469
4833236 ZroJumiaNGMob2  36921   0.00015 5.53815
4877020 ZroJumiaNGMob3  781926  0.00015 117.2889
4948833 ZroJumiaNGMob4  900899  0.00026 234.23374
4984715 ZroJumiaNGMob5  440423  0.00021 92.48883
4984722 ZroJumiaNGMob6  542272  0.00024 130.14528

第二个文件(需要获取付款字段并将它们放在同一行-不起作用):

Offer.name  name    Stat.impressions    Stat.conversions    Stat.clicks payout
Aliexpress Online Store - revShare International    ZroJumiaNGMob1  0   205 83598   47.4551
Aliexpress Online Store - revShare International    ZroJumiaNGMob2  0   13  12080   1.6562
Aliexpress Online Store - revShare International    ZroJumiaNGMob3  0   50  14750   13.0269
Aliexpress Online Store - revShare International    ZroJumiaNGMob4  0   17  7108    3.5583
Aliexpress Online Store - revShare International    ZroJumiaNGMob5  0   25  11045   2.1942
Aliexpress Online Store - revShare International    ZroJumiaNGMob6  0   70  27187   12.3148

1 个答案:

答案 0 :(得分:0)

您可以按照以下步骤合并2个csv文件

$csv1ToArray = parseCsv('FILEPATH');
$csv2ToArray = parseCsv('FILEPATH');
$res = [];
array_walk($csv1ToArray, function($v, $k) use (&$res, $csv2ToArray){
    $res[$k] = array_merge($v,$csv2ToArray[$k]);
});
writeTocsv('merged.csv', $res);
//function to write in csv file
function parseCsv($file){
  if (($handle = fopen($file, "r")) !== FALSE) {
    while (($line = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $data[] = $line;
    }
  }
 return $data;
}
// function to parse csv in array
function writeTocsv($file, $rows){
  if(!empty($file) && count($rows) > 0 ){
    $fp = fopen($file, 'w');
    foreach ($rows as $fields) {
        fputcsv($fp, $fields);
    }
    fclose($fp);
  }
}