Skip to content
Advertisement

PHP – fgetcsv loop for get data from csv file column by column

I have a CSV file with 31 columns and 24 rows. I need with fgetcsv (or maybe another solution) to pass in the CSV and get data column by column. I have one solution:

JavaScript

The for loop is working but $data[$col] only gets data from the first column of the CSV, it doesn’t get data from $data[$col] when $col is 2, 3, 4, …, 31.

Where did I make a mistake, and what is the problem? The code looks okay to me, but I think that I don’t know something about the fgetcsv function.

max is filesize of CSV, fgetcsv see that like max size of file. No matter what is in fgetcsv they see just first column, not loop every time when $col changes.

JavaScript

Advertisement

Answer

In your code:

JavaScript

you are trying to fetch all rows from the file 32 times. The first iteration fetches all the rows from the file, since the while loop ends when fgetcsv returns false (when there is no more data to read).

I need with fgetcsv(or maybe other solution) to pass in csv and get data column by column.

You can not read data column by column, since the file is read line by line, and the lines represent the table rows. If you want to iterate the table data by columns, you can read the entire table into an array, then exchange rows and cells:

JavaScript

So you don’t need the outer loop iterating the column “indices”, as fgetcsv already fetches an array for the next row where the items contain the cell values:

JavaScript

At least, put the loop into the while loop that fetches the rows. If you want to iterate the cells, iterate the value returned by fgetcsv.

Example

JavaScript

Output

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement