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
  • 952
  • 10
  • 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);
    }
    ?>
tirenweb
  • 30,963
  • 73
  • 183
  • 303
Sanoob
  • 2,466
  • 4
  • 30
  • 38
3

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 De Silva
  • 3,555
  • 6
  • 35
  • 51
  • thanks for the response, i don't want to search rows ( lines ) instead only columns though ? – Woolff Aug 09 '15 at 19:19
  • 1
    you may find this question useful http://stackoverflow.com/questions/15191682/how-to-read-specific-columns-of-a-csv-file-with-php – Ruwanka De Silva Aug 10 '15 at 02:41
3

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
  • 12,171
  • 2
  • 25
  • 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);
?>