php - 如何访问对象 Twitter API 中的对象?
问题描述
我已经开始使用 Twitter API 和 Abraham 的TwitterOAuth
包装器来检索 Twitter 数据,但我不知道如何访问返回的数组中的对象。数据的结构如下:
array(1) { [0]=> object(stdClass)#462 (24) {
["created_at"]=> string(30) "Tue Sep 11 03:30:54 +0000 2018"
["id"]=> int(120823024720)
["id_str"]=> string(19) "1268383623782373"
["text"]=> string(141) "RT @user: tweet tweet tweet tweet tweet"
["truncated"]=> bool(false)
["entities"]=> object(stdClass)#463 (4) {
["hashtags"]=> array(0) { }
["symbols"]=> array(0) { }
["user_mentions"]=> array(1) {
[0]=> object(stdClass)#464 (5) {
["screen_name"]=> string(6) "user"
["name"]=> string(3) "username"
["id"]=> int(12361328)
["id_str"]=> string(8) "12342312"
["indices"]=> array(2) {
[0]=> int(3)
[1]=> int(10) } } }
["urls"]=> array(0) { } }
["source"]=> string(82) "Twitter for iPhone"
["in_reply_to_status_id"]=> NULL
["in_reply_to_status_id_str"]=> NULL
["in_reply_to_user_id"]=> NULL
["in_reply_to_user_id_str"]=> NULL
["in_reply_to_screen_name"]=> NULL
["user"]=> object(stdClass)#465 (42)
还有更多层,因为推文实际上非常复杂。我可以访问对象之前的前几条数据entities
,但是,我如何访问这些子层?比如说,我想访问用户的屏幕名称。我试过这样:
$data->entities->user_mentions->screen_name;
但我真的不知道对这些嵌套数据进行排序。如何导航此数据结构并访问它的不同部分?
解决方案
首先,响应是一个数组。所以要从数组中获取第一项,
//get first item
$tweet = $data[0];
//user_mentions is also an array
$mention = $tweet->entities->user_mentions[0];
//now you can access the screen name with
$mention->screen_name;
如果你想遍历一系列推文,
foreach( $data as $tweet ) {
$mention = $tweet->entities->user_mentions[0];
echo $mention->screen_name;
}
推荐阅读
- api - OCAPI OAuth 验证
- typescript - 需要 TypeScript 数组中的特定项目
- javascript - 将对象数组转换为具有不同对象和数组的对象
- php - 如何使用某些字段创建belongToMany?
- class - 我的 PHP DI 无法正常工作并返回 NULL
- java - 如何从 Firebase 数据库中删除消息?
- asp.net-core - 从邮递员验证 JWT 令牌
- c++ - C++中最简单程序的问题
- android - 在 Android Xamarin Forms 中压缩视频时出现视频转码器问题
- javascript - Node.js 为什么 RegExp() 用 \ 抛出错误?