Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
541 views
in Technique[技术] by (71.8m points)

parse csv file php

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.

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.

How would I do that?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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];
}

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];
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...