0

我有以下代码,一个函数获取用户名列表并将它们放入数组中,然后执行名为函数 get_all_friends 的函数,代码工作正常且没有错误,我的问题是如果我有大量用户名可以说是 10k,如何调整代码?

就像从文件中读取包括所有用户名名称并将它们放入数组中一样

$file_handle = fopen("users.txt")

请指教 !

<?PHP
    $user1 = "usernamehere";
    $user2 = "usernamehere";
    $user3 = "usernamehere";
    $u[] = $user1;
    $u[] = $user2;
    $u[] = $user3;

    function get_all_friends($users) 
    {
        $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, TOKEN_KEY, TOKEN_SECRET);
        $list = array();
        foreach($users as $user)
        {
            $result = $connection->get( 'friends/ids', array(
            "screen_name"=> $user)
            );

            foreach($result->ids as $friend) 
            {
                $list[] = $friend;
            }

        }
        return $list;
    }

    //call the function
    $result = get_all_friends($u);

    foreach($result as $res)
    {
        $query = "INSERT INTO friends (userid, name, grade, flag) VALUES ($res, 'name', 100, 0 ) ";
        mysql_query($query);    
    }

    //to print the databse result
    echo "row<br />";
    $res = mysql_query("SELECT * FROM friends");  
    while ($row = mysql_fetch_assoc($res)) 
    {
        print_r($row);
    }
?>
4

2 回答 2

1

类似以下的东西应该可以工作(未经测试):

$filename = "users.txt";
$file_handle = fopen($filename, "r");
$contents = fread($file_handle, filesize($filename));
$usernames = preg_split("/ (,|\\n) /", $contents);
fclose($file_handle);

用户名必须用逗号或换行符分隔。

虽然,如果您确定用户名将仅由新行或逗号分隔,则此代码会更快:

$filename = "users.txt";
$file_handle = fopen($filename, "r");
$contents = fread($file_handle, filesize($filename));
// new line:
$usernames = explode("\n", $contents);
// or comma:
$usernames = explode(",", $contents);
fclose($handle);

请仅选择 $usernames 定义之一。

于 2012-09-17T08:43:56.987 回答
0

专门回答这个问题,检查file(..)- “将整个文件读入数组”

http://php.net/manual/en/function.file.php

尽管您可能不想这样做,但如果文件很大,您最好按顺序阅读或进行某种直接导入。

于 2012-09-17T08:43:33.743 回答