I'm getting JSON data back like this:
{
"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:
$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?
asked May 16, 2018 at 2:31
1 Answer 1
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;
-
Thanks! Excellent explanation that'll help me next time.jonmrich– jonmrich2018年05月16日 02:48:04 +00:00Commented May 16, 2018 at 2:48
lang-php
$distance_data = json_decode($output, true); $distance_data['rows'][0]['elements'][0]['duration']['value']
. Note: if you don't passtrue
as 2nd paramater to json_decode, the result will be stdObject instead of array.