2

Having trouble searching CSV file by Column. For example, I have the following CSV file:

NAME, HAS AN IPHONE, HAS ANDROID

bob, yes, no,

fred, no, yes,

How could I search column 2 for a 'yes' value using php, then return only the rows with "yes" in second column results?

Aaron Morefield
  • 940
  • 11
  • 18
Woolff
  • 43
  • 1
  • 1
  • 6

4 Answers4

5

I think, This can help you. Read about fgetcsv

 <?php

    $result  = [];
    if (($handle = fopen("test.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
          if($data[1] == 'yes') //Checks second column is 'yes' 
              array_push($result, $data);
        }
        fclose($handle);

      var_dump($result);
    }
    ?>
ziiweb
  • 29,901
  • 71
  • 176
  • 297
Sanoob
  • 2,398
  • 3
  • 27
  • 35
2

Have you tried anything if so please post that also, you may find this helpful

$csv = array_map('str_getcsv', file('data.csv'));

foreach($csv as $line){
    if($line[1] == 'yes'){
        //do what ever you want
        echo "found yes";
    }
}
Ruwanka Madhushan
  • 3,195
  • 5
  • 33
  • 48
2

Assuming you have already parsed the csv file into an array.
The second parameter of array_keys function is mixed $search_value

If specified, then only keys containing these values are returned.

To search a specific column, use array_column:

$res = array_keys(array_column($csv, 1), "yes");

See test at eval.in; This would return keys of of all "yes" matches in the second column.

Community
  • 1
  • 1
Jonny 5
  • 11,591
  • 2
  • 23
  • 42
0

Well this is what i tried and it worked for searching for a value in rows. Then you can get the values of the rows and use it.

<?php

$file = fopen("test.csv", "r");
$str = "n@gmail.com";
while (($data = fgetcsv($file)) !== false)
{
    if(in_array($str, $data))
    {
        foreach ($data as $i)
        {
            echo $i."<br>";
        }   
    }
}
fclose($file);
?>