0

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

1 Answer 1

2

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 />";
  }
}  
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.