Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

csv

key

So I have a CSV file that looks like this:

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

How can I insert this into an array that looks like so

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

This is what I currently had to get a single numerical based value on a one tier CSV

      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 replies, but I still see a potential issue. With these solutions, wouldn't the values store in this way:

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

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

like image 383
ThinkingInBits Avatar asked Aug 05 '10 14:08

ThinkingInBits


2 Answers

You can use fgetcsv() to read a line from a file into 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);
like image 59
Hollance Avatar answered Sep 22 '22 00:09

Hollance


Assuming that the first row in the CSV file contains the column headers, this will create an associative array using those headers for each row's data:

$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);
like image 30
ReK_ Avatar answered Sep 20 '22 00:09

ReK_