如何通过这个数组循环以获得我需要的东西?

时间:2011-07-18 13:21:49

标签: php arrays

我正在使用twitter API来检索我的所有推文。但是,我似乎无法获得“expanded_url”和“hashtag”属性。可以在https://dev.twitter.com/docs/api/1/get/statuses/user_timeline找到此特定API的文档。我的代码如下:

$retweets = 'http://api.twitter.com/1/statuses/user_timeline.json?  include_entities=true&include_rts=true&screen_name=callmedan';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $retweets);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$curlout = curl_exec($ch);
curl_close($ch);
$response = json_decode($curlout, true);
$tweet_number = count($response);

for($i = 0;$i < $tweet_number;$i++)
{
    $url = $response['entities']['urls'];
    $hashtag = $response['entities']['hashtags'];
    $text = $response[$i]['text'];

    echo "$url <br />";
    echo "$hashtag <br />";
    echo "$text <br />";
    echo "<br /><br />";

}

我收到一条错误消息“通知:未定义的索引:实体。”

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

你应该这样做(如果$ response是一个数组,你必须访问正确的索引):

$url = $response[$i]['entities']['urls'];
$hashtag = $response[$i]['entities']['hashtags'];
$text = $response[$i]['text'];

否则使用foreach:

foreach ($response as $r){
    $url = $r['entities']['urls'];
    $hashtag = $r['entities']['hashtags'];
    $text = $r['text'];

答案 1 :(得分:0)

您正在使用整数递增的for循环,但不使用$i索引。相反,请使用foreach

foreach($response as $tweet)
{
    $url = $tweet['entities']['urls'];
    $hashtag = $tweet['entities']['hashtags'];
    $text = $tweet['text'];

    echo "$url <br />";
    echo "$hashtag <br />";
    echo "$text <br />";
    echo "<br /><br />";

}