2011-05-09 39 views
1

我使用fgetcsv解析CSV文件,特别是使用$ line_of_text。我想呼应所有具有共享国家的城市,但我想要消除城副本,这样,如果,例如,巴黎发生了200次也只是相呼应一次,沿着单一的回声法国的其他不同的城市,无论的实例数量。如何使用PHP的fgetcsv消除CSV文件副本?

我的直觉是,我需要到城市值存储在一个数组,然后使用array_unique删除重复,但不幸的是这已经超出我目前的PHP的能力。任何帮助深表感谢,我已经尝试了一切权力!

<?php 
    $display = 100; 
    $counter = 1; 
    $country = $_GET['country']; 
    echo "<ol>"; 
    $file_handle = fopen("csv/file.csv", "r"); 
    while (($line_of_text = fgetcsv($file_handle, 1024, ",")) !== false) { 
     if ($line_of_text[13] == $country) { 
      echo "<li>City:" . $line_of_text[15]) . "</li>"; 

      $counter++; 
      if ($counter == $display) { 
       break; 
       echo "</ol>"; 
      } 
     } 
    } 
    fclose($file_handle); 
?> 

回答

1

刚刚从内存的工作,尝试像

<?php 
    $display = 100; 
    $counter = 1; 
    $country = $_GET['country']; 
    $storedcountries = array();//Store countries that have already been read 
    echo "<ol>"; 
    $file_handle = fopen("csv/file.csv", "r"); 
    while (($line_of_text = fgetcsv($file_handle, 1024, ",")) !== false) { 
     if ($line_of_text[13] == $country && !in_array($storedcountries, $line_of_text[13]) {//Make sure the country is not already stored in the $storedcountries array 
      echo "<li>City:" . $line_of_text[15]) . "</li>"; 

      $counter++; 
      if ($counter == $display) { 
       break; 
       echo "</ol>"; 
      } 
      $storedcountries[] = $line_of_text[15]; 
     } 
    } 
    fclose($file_handle); 
?> 
+0

欢呼,但我得到解析错误:语法错误,意想不到的'{'第102行 – javascriptless 2011-05-09 01:32:14

+0

对不起,为清楚起见,解析错误发生在这一行: if($ line_of_text [13] == $ country !&& in_array($ storedcountries,$ line_of_text [13]){ – javascriptless 2011-05-09 01:32:55

+0

刚把周围走错路的参数:($ line_of_text [13],$ storedcountries)编制完善有一次,我定了 - 传说! – javascriptless 2011-05-09 01:57:44

1

您可以简化您的代码位:

// read in file 
$csv = array_map("str_getcsv", file("csv/file.csv")); 
$cities = array(); 

// loop for countries 
foreach ($csv as $line) { 
    if ($line[13] == $country) { 
     $cities[] = $line[15]; // append to new array 
    } 
} 

// unique cities 
$cities = array_unique($cities); 
$cities = array_slice($cities, 0, 100); // max 100 

// output 
foreach ($cities as $name) { print "<li>City: $name</li>"; } 

你应该尽量保持处理逻辑与输出分离这样。