Zac*_*ner 6 php arrays facebook-graph-api
我正在尝试使用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"
}
],
Run Code Online (Sandbox Code Playgroud)
如何使用PHP选择类型为"college"的PHP?这是我用来阅读它的内容:
$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));
Run Code Online (Sandbox Code Playgroud)
所以这个名字就是$ 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);
}
Run Code Online (Sandbox Code Playgroud)
结果将是这样的:
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)
Run Code Online (Sandbox Code Playgroud)
一个更简单的技巧是使用json_decode并将第二个param设置为true,这会强制结果为数组而不是stdClass.
$user = json_decode(file_get_contents($graph_url), true);
Run Code Online (Sandbox Code Playgroud)
如果你使用数组,你必须将大学检索foreach更改为:
foreach($user["education"] as $education) {
if($education["type"] == "College") {
$college = $education;
break;
}
}
Run Code Online (Sandbox Code Playgroud)
结果将是:
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)
Run Code Online (Sandbox Code Playgroud)
虽然两者都是有效的,但在我看来,你应该使用数组,它们更容易,更灵活,适合你想做的事情.
| 归档时间: |
|
| 查看次数: |
6205 次 |
| 最近记录: |