开发者

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

开发者 https://www.devze.com 2023-01-10 03:57 出处:网络
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

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")) {

    开发者_如何学C      $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?


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


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


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


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

  }


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

精彩评论

暂无评论...
验证码 换一张
取 消