如何使用PHP的fgetcsv消除CSV文件中的重复项?

时间:2011-05-09 00:43:52

标签: php fopen fgetcsv fclose

我正在使用fgetcsv解析CSV文件,特别是使用$ line_of_text。我想呼应所有拥有共享国家的城市,但我想消除城市重复,以便例如,如果巴黎发生了200次,那么只会回应一次,对于法国其他不同城市的一次回声他们的实例数量。

我的预感是我需要将城市值存储在数组中,然后使用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);
?>

2 个答案:

答案 0 :(得分: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);
?>

答案 1 :(得分: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>"; }

您应该尝试将处理逻辑和输出分开,就像这样。