3

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?

6
  • 1
    Depends on your code to read the CSV. Commented Aug 9, 2015 at 16:25
  • i dont knwo what you mean AbraCadaver ?? $file = fopen("example.csv","r"); $fileholder = fgetcsv($file); Commented Aug 9, 2015 at 16:30
  • You need to print out "yes" and "no" or count them? What's the purpose for it? Commented Aug 9, 2015 at 16:34
  • well for example i would just want to print all the users who have yes in there second column. Not displaying those with a no in the second column. Commented Aug 9, 2015 at 16:38
  • How is it possible that you are even asking this question? Commented Aug 9, 2015 at 17:03

4 Answers 4

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);
    }
    ?>
Sign up to request clarification or add additional context in comments.

1 Comment

It should be array_push($result, $data);
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.

Comments

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";
    }
}

2 Comments

thanks for the response, i don't want to search rows ( lines ) instead only columns though ?
you may find this question useful stackoverflow.com/questions/15191682/…
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 = "[email protected]";
while (($data = fgetcsv($file)) !== false)
{
    if(in_array($str, $data))
    {
        foreach ($data as $i)
        {
            echo $i."<br>";
        }   
    }
}
fclose($file);
?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.