1

I have a semi-large CSV file with 2,000 rows and about 25 columns. I need to know how to convert the cells to a variable. If even possible. IE convert cell A3 to a php variable then which I can echo out when a user clicks a button. Sort of a Generator I'm making.

I could not find anything of real use on the internet.

4

2 回答 2

1

PHP 有一个功能:fgetcsv. 您使用它返回文件资源中的下一行(然后推进指针)。它将返回一个数组,其中每个元素都是 CSV 中的一个字段。

你会像这样使用它:

$csv = array();

if (FALSE !== $handle = fopen("example.csv", "r"))
{

  while (FALSE !== $row = fgetcsv($handle))
  {
    $csv[] = $row;
  }

}

然后,您可以执行以下操作,假设 CSV 中的第一行包含列标题,以将数值数组转换为关联数组:

$new_csv = array();

foreach ($csv as $row)
{

  $new_row = array();

  for ($i = 0, $n = count($csv[0]); $i < $n; ++$i)
  {
    $new_row[$csv[0][$i]] = $row[$i]; 
  }

  $new_csv[] = $new_row;

}

然后,如果您想访问第一行的“名称”列(其中“第零”行是列标题),您可以调用$new_csv[1]['name']. 或者,如果没有标题行,并且您知道“名称”列是第一列,则可以调用$csv[0][0].

于 2013-02-10T21:05:14.820 回答
0

看一下fgetcsvandstr_getcsv方法(参见示例链接)。

于 2013-02-10T20:56:12.837 回答