質問

I have a csv file in that i want to search in a specific column for a value, if found the corresponding row should be set in an array. That i already have working, but if there are multiple rows that have that value, with my code only the last stands in the variable, because it overrides the previous entrys.

How can i make it so that i can echo all rows separatly ? maybe in a multidimensional array ? Im a beginner in php, help is greatly apreciated. Thanks

$search = $station;
if (($handle = fopen("CSV-data/airport-frequencies.csv", "r")) !== FALSE) {
  $row=0;
  $csv_row = array();
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($data[2] == $search) {
      $csv_row = $data;
    }
  }
  fclose($handle);
    echo $csv_row[3] . "<br />"; //type
    echo $csv_row[4] . "<br />"; //description
    echo $csv_row[5] . "<br />"; //frequency
    echo "<hr /><br />";
}   
役に立ちましたか?

解決

You are right, you need an array of arrays. So something like this should work for you:

$search = $station;
if (($handle = fopen("CSV-data/airport-frequencies.csv", "r")) !== FALSE) {
  $row=0;
  $csv_row = array();
  while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
    if ($data[2] == $search) {
      $csv_row[] = $data;
    }
  }
  fclose($handle);
  foreach ($csv_row as $row) {
    echo $row[3] . "<br />"; //type
    echo $row[4] . "<br />"; //description
    echo $row[5] . "<br />"; //frequency
    echo "<hr /><br />";
  }
}  
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top