繁体   English   中英

通过 PHP 中的 Facebook 图表 API 获得教育

[英]Getting Education with Facebook Graph API in PHP

我正在尝试使用 stdclass 从 Facebook 的图表 API 获取教育信息。 这是数组:

 "username": "blah",
   "education": [
      {
         "school": {
            "id": "[removed]",
            "name": "[removed]"
         },
         "year": {
            "id": "[removed]",
            "name": "[removed]"
         },
         "type": "High School"
      },
      {
         "school": {
            "id": "[removed]",
            "name": "[removed]"
         },
         "year": {
            "id": "[removed]",
            "name": "[removed]"
         },
         "type": "College"
      }
   ],

如何使用 PHP 到 select 类型为“college”的那个? 这是我用来阅读它的内容:

 $token_url = "https://graph.facebook.com/oauth/access_token?"
   . "client_id=[removed]&redirect_uri=[removed]&client_secret=[removed]&code=".$_GET['code']."";


 $response = file_get_contents($token_url);


 parse_str($response);

 $graph_url = "https://graph.facebook.com/me?access_token=" 
   . $access_token;


     $user = json_decode(file_get_contents($graph_url));

所以名称将是 $user->name。

我尝试了 $user->education->school 但没有奏效。

任何帮助,将不胜感激。

谢谢!

JSON 文档中的教育是一个数组(注意它的项目被[ ]包围),所以你要做的是:

// To get the college info in $college
$college = null;
foreach($user->education as $education) {
    if($education->type == "College") {
        $college = $education;
        break;
    }
}

if(empty($college)) {
    echo "College information was not found!";
} else {
    var_dump($college);
}

结果将是这样的:

object(stdClass)[5]
  public 'school' => 
    object(stdClass)[6]
      public 'id' => string '[removed]' (length=9)
      public 'name' => string '[removed]' (length=9)
  public 'year' => 
    object(stdClass)[7]
      public 'id' => string '[removed]' (length=9)
      public 'name' => string '[removed]' (length=9)
  public 'type' => string 'College' (length=7)

一个更简单的技巧是使用 json_decode 并将第二个参数设置为 true,这会强制结果为 arrays 而不是 stdClass。

$user = json_decode(file_get_contents($graph_url), true);

如果您使用 go 和 arrays,则必须将大学检索 foreach 更改为:

foreach($user["education"] as $education) {
    if($education["type"] == "College") {
        $college = $education;
        break;
    }
} 

结果将是:

array
  'school' => 
    array
      'id' => string '[removed]' (length=9)
      'name' => string '[removed]' (length=9)
  'year' => 
    array
      'id' => string '[removed]' (length=9)
      'name' => string '[removed]' (length=9)
  'type' => string 'College' (length=7)

虽然两者都是有效的,但在我看来,你应该使用 go 和 arrays,它们更容易、更灵活地完成你想做的事情。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM