1

我正在使用 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);
?>
4

2 回答 2

2

您可以稍微简化一下代码:

// 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>"; }

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

于 2011-05-09T00:57:04.343 回答
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);
?>
于 2011-05-09T00:52:30.387 回答