Home > database >  How to count specific column data in CSV file using PHP
How to count specific column data in CSV file using PHP

Time:12-10

I have one CSV file. It contains 3 columns I want to count only the 3rd column total rows. I tried with one code but It showed the whole CSV file rows counts.

$record = file('filename.csv', FILE_IGNORE_NEW_LINES |  FILE_SKIP_EMPTY_LINES);
$total_record = count($record);
echo  $total_record; // output 6

As per the below image, I want to count only the Ph_no column. Please help me out

enter image description here

CodePudding user response:

$file = fopen('myCSVFile.csv', 'r');
$count = 0;
while (($line = fgetcsv($file)) !== FALSE) {
    $num = count($line);
    for ($i=0; $i < $num; $i  ) {
        if(!empty($line[2]) {
            $count  ;
        }
    }
}
fclose($file);
echo $count;

CodePudding user response:

You could use array_map() to run callback str_getcsv() on each element (row) in the array that is returned by file().

$arr = array_map('str_getcsv', file('./filename.csv'));

The result ($arr) would look something like this:

Array
(
    [0] => Array
        (
            [0] => First_Name
            [1] => Last_name
            [2] => Ph_no
        )

    [1] => Array
        (
            [0] => ABC
            [1] => AB
            [2] => 1234567890
        )

    ... etc.

You can then count the number of phone numbers:

$phNo = array_column($arr, 2);
$phNoCount = count($phNo) -1 ; // subtract the header
echo 'Ph_no count: ' . $phNoCount;

CodePudding user response:

Using the fgetcsv() function it is quite simple

$tot = 0;
if (($f = fopen("filename.csv", "r")) !== FALSE) {
    // read and ignore first line, titles
    fgetcsv($f, 1000, ",");
    while (($line = fgetcsv($f, 1000, ",")) !== FALSE) {
        if ( $line[2] !== '' ) {
            $tot  = $line[2];   // accumulate column 3
        }
    }
}
fclose($f);
echo $tot;

  • Related