Search code examples
phpfgetcsv

PHP fgetcsv 2 dimensional array


I have seen few similar examples but it is still not working. csv data file "data1.csv" is as below:

symbol,num1,num2
QCOM,10,100
QCOM,20,200
QCOM,30,300
QCOM,40,400
CTSH,10,111
CTSH,20,222
CTSH,30,333
CTSH,40,444
AAPL,10,11
AAPL,20,22
AAPL,30,33
AAPL,40,44

--end of file ----

$inputsymbol = QCOM ; // $inputsymbol will come from html.works fine.

I want to read the csv file and fetch lines that matches symbol = QCOM. and convert it in to array $data1 to plot line chart for num1 and num2 as below.

$data1 = array ( 
array(10,100),
array(20,200),
array(30,300),
array(40,400)
);

Note: 1. no comma at the end of each csv lines in csv datafile. 2. Multiple symbols in same file. so the lines that match symbols only
should be included in $data1.

==============

Mark's soluition solves the problem. Now to make the data access faster (for a very large csv file), I have (externally) formatted same data as below. Question is how it can automatically extract headers and then for the data1 array?

symbol,1/1/2015,1/2/2015,1/3/2015,1/4/2015
QCOM,100,200,300,400
CTSH,11,22,33,44
AAPL,10,11,12,13

Note that the number of fields in header is not fixed. (it will increase every month). But the data will also increse accordingly.


Solution

  • Not complicated:

    $inputsymbol = 'QCOM';
    
    $data1 = [];
    $fh = fopen("data1.csv", "r"));
    while (($data = fgetcsv($fh, 1024)) !== FALSE) {
        if ($data[0] == $inputsymbol) {
            unset($data[0]);
            $data1[] = $data;
        }
    }
    fclose($fh);
    

    So where exactly are you having the problem?