所以我有一个如下所示的 CSV 文件:
12345, Here is some text
20394, Here is some more text
我怎样才能把它插入到一个看起来像这样的数组中
$text = "12345" => "Here is some text",
"20394" => "Here is some more text";
这是我目前必须在一层 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.");
}
感谢您的回复,但我仍然看到一个潜在的问题。使用这些解决方案,值不会以这种方式存储:
$array[0] = 12345
$array[1] = Here is some text 20394
$array[2] = Here is some more text
如果我在上面的示例 csv 上尝试这个,数组将如何构建?
最佳答案
您可以使用 fgetcsv()
将文件中的一行读入数组。所以像这样:
$a = array();
$f = fopen(....);
while ($line = fgetcsv($f))
{
$key = array_shift($line);
$a[$key] = $line;
}
fclose($f);
var_dump($a);
关于php - 如何将 CSV 解析为以第一个值作为键的数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3415540/