How can I parse CSV into an array with the first value as a key?

So, I have a CSV file that looks like this:

12345, Here is some text
20394, Here is some more text

How to insert this into an array that looks like this

$text = "12345" => "Here is some text",
        "20394" => "Here is some more text";

This is what I currently had to get based on a numeric value for CSV level 1

      if ($handle = fopen("$qid", "r")) {

          $csvData = file_get_contents($qid);
          $csvDelim = "\r";

          $qid = array();
          $qid = str_getcsv($csvData, $csvDelim);

      } else {

          die("Could not open CSV file.");

      }

Thanks for the answers, but I still see a potential problem. With these solutions, values ​​are not saved in this way:

$array[0] = 12345
$array[1] = Here is some text 20394
$array[2] = Here is some more text

If I tried this with the csv example above, how would the array be structured?

+5
source share
5 answers

You can use fgetcsv()to read lines from a file to an array. So something like this:

$a = array();
$f = fopen(....);
while ($line = fgetcsv($f))
{
    $key = array_shift($line);
    $a[$key] = $line;
}
fclose($f);
var_dump($a);
+10
source

, CSV , , :

$filepath = "./test.csv";
$file = fopen($filepath, "r") or die("Error opening file");
$i = 0;

while(($line = fgetcsv($file)) !== FALSE) {
    if($i == 0) {
        $c = 0;
        foreach($line as $col) {
            $cols[$c] = $col;
            $c++;
        }
    } else if($i > 0) {
        $c = 0;
        foreach($line as $col) {
            $data[$i][$cols[$c]] = $col;
            $c++;
        }
    }
    $i++;
}

print_r($data);
+3

If you are reading a file, I can recommend using something like fgetcsv (). This will read each row in the CSV into an array containing all columns as values.

http://at2.php.net/fgetcsv

0
source
$csv_lines = explode('\n',$csv_text);
foreach($csv_lines as $line) {
  $csv_array[] = explode(',',$line,1);
}

edit - based on the code sent after the original question:

  if ($handle = fopen("$qid", "r")) {

      $csvData = file_get_contents($qid);
      $csvDelim = "\r"; // assume this is the line delim?

      $csv_lines = explode($csvDelim,$csvData);
      foreach($csv_lines as $line) {
        $qid[] = explode(',',$line,1);
      }

  } else {

      die("Could not open CSV file.");

  }
0
source

With your new file with two columns, $ qid should become an array with two values ​​for each row.

$csvDelim = ",";
$qid = str_getcsv($csvData, $csvDelim);
$text[$qid[0]] = $qid[1];
0
source

All Articles