tags:

views:

58

answers:

4

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?

+7  A: 

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);
Hollance
replace `fopen` with `fgetcsv`
Sarfraz
+1 elegant and efficient
Artefacto
@Sarfaz: erm, `fgetcsv` still requires a handle from `fopen`? Or did there used to be a `fread` that needed to be replaced?
Wrikken
Good stuff man, thanks!
ThinkingInBits
A: 

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

http://at2.php.net/fgetcsv

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

edit - based on code posted after 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.");

  }
clumsyfingers
This may actually do the trick... I'll get back to you :)
ThinkingInBits
Fatal error: [] operator not supported for strings in C:\xampp\htdocs\hint_updater\index.php on line 39
ThinkingInBits
Oops, haha, well, $qid is used for both the string and the array, I did not notice that. Try redeclaring $qid as an array before the "foreach" loop as you did in your code$csv_lines = explode($csvDelim,$csvData);$qid = array(); foreach($csv_lines as $line) { $qid[] = explode(',',$line,1); }Might be good to do $qid_array instead as well so you don't lose the original file string.
clumsyfingers
A: 

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

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