我有一个 PHP 程序,它可以读取上传到我的网站上的 .csv 文件。
每次上传时,文件中的字段数量都可能不同。
我想要确定 .csv 文件的大小(即字段数),并将其内容存储在一个数组中。
以下是我目前的代码:
如果有30个字段和200条记录,我想让数组的结构为
每次上传时,文件中的字段数量都可能不同。
我想要确定 .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;
}