解析csv文件php [英] parse csv file php

查看:113
本文介绍了解析csv文件php的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个csv文件,我想与php一起使用。 csv中的第一件事是列名。一切都以逗号分隔。

I have a csv file that I want to use with php. The first thing in the csv are column names. Everything is separated by commas.

我想能够将列名称作为数组名称,并且该列的所有值将在该数组名称下。所以如果在column1下有20行,那么我可以做column1 [0],而column1的第一个实例(不是列名)。

I want to be able to put the column names as the array name and all the values for that column would be under that array name. So if there were 20 rows under column1 then I could do column1[0] and the first instance (not the column name) would display for column1.

推荐答案

您要 fgetcsv 它会将CSV文件的每个作为数组。由于您希望将每个列都转换为自己的数组,因此您可以从该数组中提取元素,并将其添加到表示列的新数组。像:

You want fgetcsv it will get each row of the CSV file as an array. Since you want to have each column into its own array, you can extract elements from that array and add it to new array(s) representing columns. Something like:

$col1 = array();
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
  $col1[] = $row[0];
}

或者,您可以使用 fgetcsv 转换为2D矩阵(前提是CSV文件不会太大):

Alternatively, you can read the entire CSV file using fgetcsv into a 2D matrix (provided the CSV file is not too big) as:

$matrix = array();
while (($row = fgetcsv($handle, 1000, ",")) !== FALSE) {
  $matrix[] = $row;
}

,然后将您想要的列提取到自己的数组中:

and then extract the columns you want into their own arrays as:

$col1 = array();
for($i=0;$i<count($matrix);$i++) {
  $col1[] = $matrix[0][i];
}

这篇关于解析csv文件php的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆