You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PHP循环数组无结果:修改Twitter教程代码适配搜索API遇阻

新手PHP开发:Twitter搜索API数组遍历问题

我是个PHP新手,最近在修改《Build Your First Twitter App Using PHP in 8 Easy Steps》教程里的代码——把原来调用Twitter状态API的逻辑改成调用搜索API。之前用echo "<pre>"; print_r($string); echo "</pre>";能正常输出完整的API返回结果,但换成教程里的foreach循环后,只能拿到一些无关的标题内容,真正的推文数组内容显示不出来。下面是我的完整代码(已移除敏感访问令牌):

"", 'oauth_access_token_secret' => "", 'consumer_key' => "", 'consumer_secret' => "" ); $url = 'https://api.twitter.com/1.1/search/tweets.json'; $getfield = '?q=php'; $requestMethod = 'GET'; $twitter = new TwitterAPIExchange($settings); $string = json_decode($twitter->setGetfield($getfield) ->buildOauth($url, $requestMethod) ->performRequest(),$assoc = TRUE); // 这段代码能正常显示完整结果 // echo "
"; print_r($string); echo "
"; // 下面是出问题的foreach循环 foreach($string as $items) { echo "Tweet: ". $items['text'] . "
"; echo "Posted by: ". $items['user']['name'] . "
"; echo "Time posted: ". $items['created_at'] . "

"; } ?>

问题根源

Twitter搜索API和状态API的返回结构完全不一样!状态API返回的直接是一个包含推文对象的数组,但搜索API返回的是一个外层包装对象,真正的推文数组藏在statuses这个键下面。你现在直接遍历$string,其实是在遍历外层的那些无关键值(比如statuses、search_metadata),自然拿不到想要的推文内容。

修复方案

把foreach循环改成遍历$string['statuses']这个具体的推文数组就行,修改后的代码如下:

// 修正后的foreach循环
foreach($string['statuses'] as $items) {
    echo "Tweet: ". $items['text'] . "<br />";
    echo "Posted by: ". $items['user']['name'] . "<br />";
    echo "Time posted: ". $items['created_at'] . "<br /><hr />";
}

额外小提示

为了避免API请求失败或者结构变化导致报错,可以加个简单的判断,确保statuses字段存在且是数组再遍历:

if(isset($string['statuses']) && is_array($string['statuses'])) {
    foreach($string['statuses'] as $items) {
        echo "Tweet: ". $items['text'] . "<br />";
        echo "Posted by: ". $items['user']['name'] . "<br />";
        echo "Time posted: ". $items['created_at'] . "<br /><hr />";
    }
} else {
    echo "没有找到相关推文,或者API请求出错了!";
}

下次遇到API返回数据的问题,记得先用print_r或者var_dump仔细拆解一下数据结构,就能快速定位问题啦~

内容的提问来源于stack exchange,提问作者Flossy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.22 09:41:36