Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
949 views
in Technique[技术] by (71.8m points)

arrays - PHP Find String in CSV file

I've got a large flat file of usernames and emails in the following format:

"username", "email"
"username", "email"
"username", "email"

etc...

I need to take the email and search for the username, but for some reason it will not return a result. It works if I search opposite.

$string = "user_email@something.com";
$filename = "user_email.txt";
        $h = fopen("$filename","r");
        $flag=0;

        while (!feof ($h)) {
            $buffer = fgets($h);
            $thisarray = split(",", $buffer);

            if ($string == str_replace('"','', $thisarray[1])) { 
                $i = 1;
                $i++;
                echo '<td bgcolor="#CCFFCC"><b style="color: maroon">' . str_replace('"','',$thisarray[0]). '</b></td>';

                }   

Any ideas? Thanks!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As per reko_t's suggestion: Use fgetcsv to read individual lines of csv into arrays, until you find one where the second element matches your search term. The first element then is the username. Something like:

<?php
function find_user($filename, $email) {
    $f = fopen($filename, "r");
    $result = false;
    while ($row = fgetcsv($f)) {
        if ($row[1] == $email) {
            $result = $row[0];
            break;
        }
    }
    fclose($f);
    return $result;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...