PHP - 访问json响应中的值
我有一个访问PHP中API响应的对象返回值的需求。 API响应PHP - 访问json响应中的值
$res = {
"data": {
"first_name": "Dany",
"last_name": "mate",
"id": "1379933133290837510",
"image": {
"60x60": {
"url": "https://s-media-cache-ak0.pinimg.com/avatars/dtest_1438666564_60.jpg",
"width": 60,
"height": 60
}
}
}
}
如何访问参数 “FIRST_NAME” & “URL”?非常感谢您的帮助。我试图将响应转换为数组但不起作用
$array = get_object_vars($res);
我不知道这是否是正确的方法吗?
$res = json_decode('{
"data": {
"first_name": "Dany",
"last_name": "mate",
"id": "1379933133290837510",
"image": {
"60x60": {
"url": "https://s-media-cache-ak0.pinimg.com/avatars/dtest_1438666564_60.jpg",
"width": 60,
"height": 60
}
}
}
}');
$array = get_object_vars($res);
print_r($array);
你需要利用json_decode
做这件事。
而不是使用'get_object_vars()',你可以简单地使用'json_decode($ string,true);'。这将返回一个数组而不是一个对象。 – KhorneHoly
你是对的,一个很好的建议。 – ameenulla0007
谢谢@ ameenulla0007 – Dibish
你必须JSON解码第一:
$json = json_decode($res,true);
foreach ($json['data'] as $data)
{
echo $data['first_name'];
};
<?php
$pp = json_decode('{
"data": {
"first_name": "Dany",
"last_name": "mate",
"id": "1379933133290837510",
"image": {
"60x60": {
"url": "https://s-media-cache-ak0.pinimg.com/avatars/dtest_1438666564_60.jpg",
"width": 60,
"height": 60
}
}
}
}');
$data = json_encode($pp->{'data'});
$aa = json_decode($data);
echo $aa->{'first_name'} .' & ';
$image = json_encode($aa->{'image'});
$dd = json_decode($image);
$sity = json_encode($dd->{'60x60'});
$url = json_decode($sity);
echo $url->{'url'};
?>
这似乎是JSON我,你有没有尝试'json_decode()'? – KhorneHoly
确切的答案是什么?这看起来像是php和js的组合。 – jeroen