【发布时间】:2012-02-24 17:38:51
【问题描述】:
我有一个 CSV 文件,其中包含来自 http://jotform.com/ 数据源的 26 个字段。文件用逗号分隔,字段用双引号括起来。数据包含逗号。这真的很打击。此外,CSV 都在一行中...
是否有人熟悉可以将 CSV 转换为关联数组的程序?
如果数组由标题而不是数字键索引,我会更喜欢。 我已经尝试了几乎所有的 http://us.php.net/fgetcsv 函数,但成功率为 0。
我尝试过的代码:
<?php
function get2DArrayFromCsv($file,$delimiter) {
if (($handle = fopen($file, "r")) !== FALSE) {
$i = 0;
while (($lineArray = fgetcsv($handle, 4000, $delimiter)) !== FALSE) {
for ($j=0; $j<count($lineArray); $j++) {
$data2DArray[$i][$j] = $lineArray[$j];
}
$i++;
}
fclose($handle);
}
return $data2DArray;
}
?>
$file_path = "../../Reunion-Memory-Book-Form.csv";
if (($handle = fopen($file_path, "r")) !== FALSE) {
# Set the parent multidimensional array key to 0.
$nn = 0;
while (($data = fgetcsv($handle, 0, ",")) !== FALSE) {
# Count the total keys in the row.
$c = count($data);
# Populate the multidimensional array.
for ($x=0;$x<$c;$x++)
{
$csvarray[$nn][$x] = $data[$x];
}
$nn++;
}
# Close the File.
fclose($handle);
}
print'<pre>';print_r($csvarray);print'</pre>';exit;
【问题讨论】:
-
更新了描述并添加了一些代码