twitter api在php中没有使用foreach循环

时间:2015-03-05 23:02:09

标签: php arrays api twitter foreach

我无法让foreach循环显示来自twitter api的任何数据

请参阅下面的代码。但是,它确实在print_r数组上显示数据。

感谢您提前的时间

     ini_set('display_errors', 1);
     require_once('TwitterAPIExchange.php');

 /** Set access tokens here - see: https://dev.twitter.com/apps/ **/
  $settings = array(
      'oauth_access_token' => "*******",
       'oauth_access_token_secret' => "*******",
       'consumer_key' => "********",
       'consumer_secret' => "*******"
      );


       /** Perform a GET request and echo the response **/
       /** Note: Set the GET field BEFORE calling buildOauth(); **/
       $url = 'https://api.twitter.com/1.1/search/tweets.json';
        $getfield = '?q=love+you&count=20';
        $requestMethod = 'GET';
        $twitter = new TwitterAPIExchange($settings);
        $string = json_decode($twitter->setGetfield($getfield)
         ->buildOauth($url, $requestMethod)
         ->performRequest(),$assoc = TRUE);
        if($string["errors"][0]["message"] != "") {echo "<h3>Sorry, there 
          was a problem.</h3><p>Twitter returned the following error 
       message:</p><p><em>".$string[errors][0]["message"]."
       </em></p>";exit();}


    foreach($string as $tweets) {

      echo $tweets['name'] . '<br />';

    }

    cannot get the foreach loop to display any data from the twitter api

请参阅下面的代码。但是,它确实在print_r数组上显示数据。

感谢您提前的时间

 /**here is the a sample of the array data but when the foreach loop is 
 added the screen is blank no error is dispayed no data is displayed**/ 

Array
(
    [statuses] => Array
    (
        [0] => Array
            (
                [metadata] => Array
                    (
                        [iso_language_code] => en
                        [result_type] => recent
                    )

                [created_at] => Thu Mar 05 23:16:36 +0000 2015
                [id] => 573623174589472768
                [id_str] => 573623174589472768
                [text] => @TheVampsband #TheVampsVIP Please choose me and 
    @Charlotte_94x to winShe hit tweet limitWe love you so much! We
     beg89
                [source] => Twitter for iPhone

1 个答案:

答案 0 :(得分:0)

首先,你循环错误的数组。您要查找的数组位于statuses索引下,因此请将您的循环更改为:

foreach($string['statuses'] as $tweets) {
    echo $tweets['name'] . '<br />';
}

查看您的print_r()并仔细检查子阵列的构建方式。例如。如果你想打印每个推文作者的名字,你应该修改foreach中的yor echo:

echo $tweets['user']['name'] . '<br />';

因为输出数组具有结构

array(..., 'user' => array('name' => 'Example name', ...));