medk medk - 5 months ago 10
JSON Question

Get specific value from JSON response

I have this response from Google Maps Distance Matrix API:

{
"destination_addresses" : [ "334-350 Hicks St, Brooklyn, NY 11201, USA" ],
"origin_addresses" : [ "565-569 Vermont St, Brooklyn, NY 11207, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "6.5 mi",
"value" : 10410
},
"duration" : {
"text" : "34 mins",
"value" : 2045
},
"status" : "OK"
}
]
}
],
"status" : "OK"
}


How to exactly get the "6.5 mi" value?

I tried this but doesn't work:

$distance = $response_a['rows'][0]['elements'][0]['distance']['text'];

Answer

You received a JSON string from Google API. Decode it before using.

$arr = json_decode($response_a, true);
echo $arr['rows'][0]['elements'][0]['distance']['text'];