2011-05-09 38 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>"; } 

你應該儘量保持處理邏輯與輸出分離這樣。