[英]Parsing “Nested” Array in PHP
I'm getting JSON data back like this: 我像这样返回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"
} }
I need to get the distance value and duration value as variables. 我需要获取距离值和持续时间值作为变量。
So, I know I need to decode this JSON: 因此,我知道我需要解码此JSON:
$distance_data = json_decode($output);
And I've tried a ton of variations like: 我已经尝试了很多变化,例如:
$duration_value = $distance_data['rows']['elements']['duration']['value']);
But I know this isn't right. 但是我知道这是不对的。 Can someone point me in the right direction? 有人可以指出我正确的方向吗?
You're getting a mixture of objects and arrays. 您将得到对象和数组的混合体。 Here's a full run through of your example. 这是您的示例的完整介绍。
// 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.