如何在一个变量中组合数组值

时间:2012-03-10 11:20:43

标签: php arrays loops

所以我开始研究这个Twitter脚本,针对那些推特关于我的网站的用户,我想用cron job来设置它,感谢他们这样做。这是它的工作原理:

  1. 从搜索页面解析用户名(共15个)

  2. 循环浏览所有15个用户名,如果在twitter.txt文件中找到它 它将停止脚本

  3. 如果在twitter.txt文件中找不到用户名,则会写入 twitter.txt文件的用户名,然后向该用户发送推文。 (twitter.txt文件有助于防止向同一用户发送重复的推文)

  4. 所以我的问题是这个脚本目前一次发送15条推文,这将被视为垃圾邮件。所以我需要帮助才能将用户名合并为3条推文。因此每条推文将包含5个用户名。你将在脚本的底部看到我有变量来存储推文的用户名。

    //cURL
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, "http://search.twitter.com/search.atom?q=MYWEBSITE");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    $twitter = curl_exec($curl);
    curl_close($curl); 
    
    //search html source page for user names
    preg_match_all('/\<uri\>http\:\/\/twitter\.com\/(.*?)\<\/uri\>/', $twitter, $usernames);
    
    //open the twitter text file and prepare for writing
    $twitter = fopen("twitter.txt", "a");
    
    //contents of the twitter text file (holds the twitter user names)
    $contents = file_get_contents("twitter.txt");
    
    //loop through each user name
    foreach($usernames[1] as $username) { 
        //if user name is found in the twitter text file it states "Found" and script stops
        if (strpos($contents, $username) !== FALSE) {
            echo $username . " - <font color=\"red\">Found</font><br />";
        //if user name is not found in the twitter text file it records the user name and tweets
        } else {
            //write to twitter text file
            fwrite($twitter, $username."\r\n");
    
            //shows what user names were recorded
            echo $username . "<br />";
    
            //user names for tweets
            //this is where i need help dividing the usernames into these variables
            $usernames_set_one = "";
            $usernames_set_two = "";
            $usernames_set_three = "";
    
            //tweet
            $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, OAUTH_TOKEN, OAUTH_SECRET);
            $content = $connection->get('account/verify_credentials');
    
            //twitter message
            $connection->post('statuses/update', array('status' => $usernames_set_one . ' thank you for tweeting about my website.' ));
            $connection->post('statuses/update', array('status' => $usernames_set_two . ' thank you for tweeting about my website.' ));
            $connection->post('statuses/update', array('status' => $usernames_set_three . ' thank you for tweeting about my website.' ));
    
            return $connection;
        }
    
    }
    
    //close the twitter text file no further writing
    fclose($twitter);
    

2 个答案:

答案 0 :(得分:0)

您可以使用while loop代替foreach,然后访问用户名:

  

$用户名[1] [$ i]于;

     

$用户名[1] [$ I + 1];

     

$用户名[1] [$ I + 2];

例如:

$i = 0;
$count = count($usernames[1]);
while($i < $count - 3) //we will use $i+2 after all
{

$i++;
}

答案 1 :(得分:0)

将这3个变量更改为数组,当第一个变量满时,将用户名添加到第二个数组,然后添加到第三个数组。发布到Twitter时,只需将名称加入implode()