获得教育与PHP Facebook的图形API [英] Getting Education with Facebook Graph API in PHP
问题描述
我试图让使用stdClass的Facebook的图形API的教育信息。这里的数组:
I'm trying to get the education info from Facebook's graph API using stdclass. here's the array:
"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来选择一个,类型为大学?下面是我用读它是什么:
How can I use PHP to select the one with type "college"? Here's what I'm using to read it:
$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));
所以名称将是$用户可>名称。
So the name would be $user->name.
我试过$用户可>教育 - >学校,但没有奏效。
I tried $user->education->school but that didn't work.
任何帮助将是AP preciated。
Any help would be appreciated.
谢谢!
推荐答案
教育您的JSON文件是一个数组(请注意,它的项目被包围的 [] ),所以你必须做什么是:
Education in your JSON document is an array (notice that its items are surrounded by [ ]), so what you have to do is:
// 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);
}
其结果会是这样的:
The result would be something like:
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_de code与第二个参数设置为true,强制的结果是数组,而不是stdClass的。
An easier trick would be to use json_decode with the second param set to true, which forces the results to be arrays and not stdClass.
$user = json_decode(file_get_contents($graph_url), true);
如果您使用数组去,你必须改变高校检索的foreach为:
If you go with arrays, you have to change the college retrieval foreach to:
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)
虽然两者都是有效的,在我看来,你应该使用数组去,他们更容易和更灵活的为你想要做什么。
Although both are valid, in my opinion you should go with arrays, they are easier and more flexible for what you want to do.
这篇关于获得教育与PHP Facebook的图形API的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!