【发布时间】:2015-06-25 00:09:17
【问题描述】:
我有一个 PHP 例程,它读取已上传到我的站点的 .csv 文件。
文件中的字段数可能因上传而异。
我希望能够确定 .csv 文件的大小(字段数),然后将其内容存储在一个数组中。
这是我目前所拥有的:
//get the csv file
$file = $_FILES[csv1][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into array
$dataline = fgetcsv($handle,1000,",","'");
$fieldnum = count($dataline);
$recordloop = 0;
while ($dataline)
{
for ($fieldloop=0; $fieldloop <$fieldnum; $fieldloop++)
{
//this is the bit that is wrong
$dataarray[]=array($dataline[$fieldloop]);
}
$data = fgetcsv($handle,1000,",","'");
$recordloop++;
}
例如,如果有 30 个字段和 200 条记录,我试图让数组成为结构 $dataarray[200][30]。
如何将数据放入此结构的数组中?
示例 .csv:
Row 1 will be field headings
Name, Gender, Ethnicity, DOB, etc .... the number of fields is not fixed - it could be from 30 to 40 fields in this row
Rows 2 onwards will be the records
John, M, British, 10/04/49, etc
Simon, M, British, 04/03/65, etc
回答 - 做了我想做的事
$file = $_FILES[csv1][tmp_name];
$handle = fopen($file,"r");
$matrix = array();
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE)
{
$matrix[] = $row;
}
【问题讨论】:
-
您可以使用 csv 样本进行编辑吗?
-
你的问题解决了吗?我的一个答案对您有用,记得检查已接受;-)
标签: php arrays algorithm csv multidimensional-array