user11083048
user11083048

Reputation:

parse CSV file in PHP by column

I want to open CSV (comma separated value) file in PHP by column, i want to take all datas from 3 columns. I tried with this code, but this only shows me data by row:

  $row = 1;
    if (($handle = fopen("ut.csv", "r")) !== FALSE) {
      while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $num = count($data);
        echo "<p> $num fields in line $row: <br /></p>\n";
        $row++;
        for ($c=0; $c < $num; $c++) {
            echo $data[$c] . "<br />\n";
        }
      }
      fclose($handle);
    }

How i can take all datas from one column ?

EXAMPLE: This i my file in Excel, which is exported to SCV: http://prntscr.com/mzcfcw

I want to take in php values from colum Name and Price and find duplicate values in column Name, compare their prices.

Upvotes: 1

Views: 1864

Answers (1)

matwr
matwr

Reputation: 1571

fgetcsv parses the given handle line by line (rows). It isn't possible to parse a csv file by column using core php. However, if you know the position of the 3 columns for which you wish to access the values, you could simply ignore all other columns:

 //position (zero indexed) of required columns
 $columnsToProcess=[0,3,4]
 for ($c=0; $c < $num; $c++) {
 //do something with value if column's index is in the required columns array 
            if(in_array($c,$columnsToProcess)){
                //value at position $c equals $data[$c]
                echo $data[$c] . "<br />\n";
             }          
        }

Moe info about fgetcsv : http://php.net/manual/en/function.fgetcsv.php

Upvotes: 2

Related Questions