如何使用PHP的fgetcsv从CSV文件中消除重复项? [英] How do I eliminate duplicates from a CSV file using PHP's fgetcsv?

查看:159
本文介绍了如何使用PHP的fgetcsv从CSV文件中消除重复项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用fgetcsv(特别是使用$ line_of_text)解析CSV文件.我想回显所有具有共同国家的城市,但是我想消除重复的城市,例如,如果发生200次巴黎,它将仅回响一次,而对于法国其他不同城市,则仅回声一次.实例数.

I am parsing a CSV file using fgetcsv, specifically using $line_of_text. I want to echo all the cities that have a shared country, but I want to eliminate city duplicates so that if, for example, Paris occurred 200 times it would only be echoed once, along a single echo for the other distinct cities of France regardless of their number of instances.

我的直觉是我需要将城市值存储在一个数组中,然后使用array_unique删除重复项,但是不幸的是,这超出了我当前的php能力.任何帮助深表感谢,我已经尽力了!

My hunch is that I need to store the city values in an array and then use array_unique to remove duplicates, but unfortunately this is beyond my current php abilities. Any help deeply appreciated, I've tried everything in my powers!

<?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);
?>

推荐答案

只需在内存中工作,尝试类似

Just working from memory, try something like

<?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);
?>

这篇关于如何使用PHP的fgetcsv从CSV文件中消除重复项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆