6

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?

3
  • Do comma's occur within the text? Commented Aug 5, 2010 at 14:18
  • Your delimiter should be ',', not "\r" Commented Aug 5, 2010 at 14:19
  • 2
    What you ask...it cannot be done, computers are not capable of such black magic. You'd need to write several thousand lines of code in assembler and have at least 16 cores in your computer to even attempt it. Commented Aug 5, 2010 at 14:19

5 Answers 5

11

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

2 Comments

replace fopen with fgetcsv
@Sarfaz: erm, fgetcsv still requires a handle from fopen? Or did there used to be a fread that needed to be replaced?
3

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);

Comments

0

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.

https://www.php.net/fgetcsv

Comments

0
$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.");

  }

2 Comments

Fatal error: [] operator not supported for strings in C:\xampp\htdocs\hint_updater\index.php on line 39
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.
0

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];

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.