Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

store the data of the csv file into a 2d array

Tags:

php

csv

suppose I have the following csv file called mycsv.csv

   "Date"      "order 1"   "order 2"   "order 3"          "total cost"
   01/04/2006   4 tires      1 oil       6 sparks plugs    "434.00$'
   03/08/2006   3 tires      2 oil       2 sparks plugs    "234.00$'
   03/12/2006   2 tires      0 oil       1 sparks plugs    "134.00$'

I want to know how to store the those data in a 2d array, any help will be greatly appreciated!

like image 752
smith Avatar asked Feb 06 '12 06:02

smith


People also ask

How do I convert a CSV file to a 2D array?

break each record into the one dimension array. for loop inside the first loop along to the number of columns in csv file. Assigned each value from the one dimension array into the two dimension array.

How do I convert a CSV file to a 2D list in Python?

Line 1: We import the NumPy library. Line 3-4: We open the sampleCSV file and we pass both CSVData and the delimiter to np. loadtxt () function, which returns the data into a 2D array. Line 6: We finally print the result which shows that now our CSV data converted into a 2D array.

How do I import a CSV file into a NumPy array?

Python NumPy read CSV into 2d NumPy arraytxt() and open() functions to load a CSV file into a 2Dimension NumPy Array. Call open file to open the CSV text file Use numpy. loadtxt( CSV file, delimiter) with the file as the result of the previous step and delimiter as “,” to return the data in a two-dimensional NumPy.


1 Answers

You might use fgetcsv(see: http://php.net/manual/en/function.fgetcsv.php). The difference to str_getcsv is that it takes a File resource as parameter and not a String.

You might also store each row in another Array to have a 2D Array e.g. (adjusted manual page example)

$twoDarray = array();
if (($handle = fopen("mycsv.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $twoDarray[] = $data;
    }
    fclose($handle);
}
like image 167
fyr Avatar answered Oct 06 '22 07:10

fyr