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?

6
  • 1
    Depends on your code to read the CSV. Aug 9, 2015 at 16:25
  • i dont knwo what you mean AbraCadaver ?? $file = fopen("example.csv","r"); $fileholder = fgetcsv($file);
    – Woolff
    Aug 9, 2015 at 16:30
  • You need to print out "yes" and "no" or count them? What's the purpose for it?
    – Mr.Web
    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.
    – Woolff
    Aug 9, 2015 at 16:38
  • How is it possible that you are even asking this question? 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);
    }
    ?>
1
  • 2
    It should be array_push($result, $data); Mar 1, 2021 at 8:56
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.

0
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
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);
?>

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.