我无法获得所需的输出

时间:2018-05-14 17:40:29

标签: php arrays csv

我从这个论坛获得此代码,问题是我无法获得所需的输出,首先我检查过如果前缀与我想要显示的电话号码相匹配,否则我要存储到file3.csv的所有结果。问题是,当我发出else语句时,我会得到匹配前缀的数字。有任何建议请。

$file1 ="csv/file1.csv";
$file2 ="csv/file2.csv";

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

$fileo=fopen("csv/file3.csv","w");

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])) {

           echo $line." ".$prefix_matches[1];
          }
           else{
             fputcsv($fileo,array($line),",",'"');

              }
            }
        }
        fclose($file);
    } 
     else {  
      echo  "Couldn't open file.";  
    }
  }
}

2个csv文件的结构:

file1.csv                            file2.csv
Prefix      Country             Phone Number     Country    Names

324664      Belgium             324664464546548  Belgium    Name 1
324663      Belgium             32416846141561   Belgium    Name 2
324662      Belgium             3242448488778780 Belgium    Name 3
324661      Belgium             3246611864654    Belgium    Name 4
324654      Belgium             3246546565995    Belgium    Name 5
37240880    Estonia             372408801784564  Estonia    Name 6
37240069    Estonia             3761815816515    Estonia    Name 7
37240044    Estonia             37240044646548   Estonia    Name 8
37270077    Estonia             3725468464687    Estonia    Name 9
393710      Italy               3937103585418    Italy      Name 10
393533      Italy               39655187151152   Italy      Name 11
39310       Italy               393756121321548  Italy      Name 12
4873        Poland              393755253151     Italy      Name 13
4872        Poland              4873545456684    Poland     Name 14
4866        Poland              48641468446      Poland     Name 15
4853        Poland              48666564684      Poland     Name 16
346724      Spain               4853654564654    Poland     Name 17
34663       Spain               34672445465      Spain      Name 18
34662       Spain               3466356565656    Spain      Name 19
34661       Spain               346679854654     Spain      Name 20
                                3466178945641    Spain      Name 21
                                4475376165416     UK        Name 22
                                4474577465465     UK        Name 23
                                448556371115      UK        Name 24
                                4474413154848     UK        Name 25

0 个答案:

没有答案