我正在收到这样的JSON数据:
{
"destination_addresses": [
"67-89 Pacific St, Brooklyn, NY 11201, USA"
],
"origin_addresses": [
"566 Vermont St, Brooklyn, NY 11207, USA"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "6.5 mi",
"value": 10423
},
"duration": {
"text": "35 mins",
"value": 2076
},
"status": "OK"
}
]
}
],
"status": "OK"
}
我需要将距离值和持续时间值作为变量。
所以,我知道我需要解码这个JSON:
$distance_data = json_decode($output);
我尝试了很多变化,例如:
$duration_value = $distance_data['rows']['elements']['duration']['value']);
但我知道这不对。有人能指出我正确的方向吗?
答案 0 :(得分:1)
您正在获得对象和数组的混合体。这是一个完整的例子。
// Your JSON response.
$json = '{
"destination_addresses": [
"67-89 Pacific St, Brooklyn, NY 11201, USA"
],
"origin_addresses": [
"566 Vermont St, Brooklyn, NY 11207, USA"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "6.5 mi",
"value": 10423
},
"duration": {
"text": "35 mins",
"value": 2076
},
"status": "OK"
}
]
}
],
"status": "OK"
}';
// Get JSON Object
$obj = json_decode($json);
// Let's see what's in the object.
print_r($obj);
/*
stdClass Object
(
[destination_addresses] => Array
(
[0] => 67-89 Pacific St, Brooklyn, NY 11201, USA
)
[origin_addresses] => Array
(
[0] => 566 Vermont St, Brooklyn, NY 11207, USA
)
[rows] => Array
(
[0] => stdClass Object
(
[elements] => Array
(
[0] => stdClass Object
(
[distance] => stdClass Object
(
[text] => 6.5 mi
[value] => 10423
)
[duration] => stdClass Object
(
[text] => 35 mins
[value] => 2076
)
[status] => OK
)
)
)
)
[status] => OK
)
*/
// Let's pull the value we want using the information above.
// Notice we start with an object, then rows is an array of objects, as is elements.
echo $obj -> rows[0] -> elements[0] -> duration -> value;