我需要比较两个差异文件csv的两列

时间:2018-05-14 09:27:53

标签: php csv

我是PHP语言的新手,我有2个csv文件,其中包含:前2列,第一列有一些国家/地区前缀,第二列有通讯国家名称。 第二列有2列,第一列有电话号码,第二列是通讯国家。如果我找到匹配的前缀,我需要对这2个文件进行比较,我需要删除这个号码,并将其余的电话号码添加到另一个文件中。例如:

   First File x.csv         Second file y.csv


prefix  country          country     phone number
4474    UK               UK          44793245683...  
347466  Spain            Spain       34746689211345
3278    Belgium          Belgium     324568845212.....
                         Switzerland 4189544562131...
                         UK          4474321546588464...
                         Italy       39324566546548345
                         UK          4478564684151...   

所以我想在另一个fil z.csv这个输出:

country     phone number
UK          44793245683...

Belgium     324568845212.....
Switzerland 4189544562131...
Italy       39324566546548345
UK          4478564684151... 

这意味着在这个数字中找到了前缀匹配:

Country     Phone NUmber      Match Prefix
Spain       34746689211345    347466
UK          4474321546588464  4474 

2 个答案:

答案 0 :(得分:0)

您可以使用fgetcsv读取csv文件fputcsv来编写csv文件

例如:

$x = fgetcsv('x.csv');
$y = fgetcsv('y.csv');
$z = [];
foreach $x as $row
  if $row[1] $y then add $row in $z
fputcsv('z.csv', $z);

答案 1 :(得分:0)

以下是示例文件和用法的答案:

文件一:

root@dib:~# cat 1.csv
prefix  country
4474    UK
347466  Spain
3278    Belgium

文件二:

root@dib:~# cat 2.csv
country     phone number
UK          44793245683...
Spain       34746689211345
Belgium     324568845212.....
Switzerland 4189544562131...
UK          4474321546588464...
Italy       39324566546548345
UK          4478564684151...

Php脚本:

root@dib:~# cat find_numbers.php
<?php
$file1 = $argv[1];
$file2 = $argv[2];

// Get an array of each line of the first file.
$prefix_contry = explode("\n", file_get_contents($file1));

print "Country\t Phone NUmber\t Match Prefix\n";

foreach($prefix_contry as $prefix_line) {
    // Extract numbers from begging of each line.
    if(preg_match('/^([0-9]+)/', $prefix_line, $prefix_matches)) {

        if($file = fopen($file2, "r")) {

            // Loop through second file line by line...
            while(($line = fgets($file)) !== false) {
                $line = rtrim($line);

                // Pull out number from second file.
                if(preg_match('/([0-9]+)/', $line, $matches)) {

                    // Check to see if number begins with prefix.
                    if(preg_match("/^{$prefix_matches[1]}/", $matches[1])) {
                        print("$line\t{$prefix_matches[1]}\n");
                    }
                }
            }
            fclose($file);
        } else {   print "Couldn't open file.";   }
    }
}

?>

试运行:

root@dib:~# php find_numbers.php 1.csv 2.csv
Country  Phone NUmber    Match Prefix
UK          4474321546588464... 4474
Spain       34746689211345      347466
相关问题