Mohit Garg Mohit Garg - 6 months ago 15
JSON Question

How to get the value of distance from the following JSON object?

I need to get the value 361714 from the following JSON object in PHP. The JSON is obtained using the google distance matrix api.

Link : https://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=Washington,DC&destinations=New+York+City,NY&key=AIzaSyDVfbt8uCHfFTehDjDS-z_XfYF1O-lLDAE

{
"destination_addresses" : [ "New York, NY, USA" ],
"origin_addresses" : [ "Washington, DC, USA" ],
"rows" : [
{
"elements" : [
{
"distance" : {
"text" : "225 mi",
"value" : 361714
},
"duration" : {
"text" : "3 hours 49 mins",
"value" : 13767
},
"status" : "OK"
}
]
}
],
"status" : "OK"


I have tried this :

for($f = 0; $f<count($address); $f++)
{
$url = "http://maps.googleapis.com/maps/api/distancematrix/json?units=imperial&origins=" . $for_cust_add . "&destinations=" . $for_add[$f] . "&key=AIzaSyDVfbt8uCHfFTehDjDS-z_XfYF1O-lLDAE";
$json = file_get_contents($url);
$details = json_decode($json, true);
$distance = $details['rows']['elements']['distance']['value'];
$distance_array[$f] = $distance;
}


It gives the error : elements not defined.

Answer

try with:

$distance = $details['rows'][0]['elements'][0]['distance']['value'];

the $details['rows']['elements'] is an array and you need its first element, hence the added [0]

Update - full proof of concept for the json in the question:

<?php
$json_file = '
{
   "destination_addresses" : [ "New York, NY, USA" ],
   "origin_addresses" : [ "Washington, DC, USA" ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "225 mi",
                  "value" : 361714
               },
               "duration" : {
                  "text" : "3 hours 49 mins",
                  "value" : 13767
               },
               "status" : "OK"
            }
         ]
      }
   ]
}';

$details = json_decode($json_file, true);
$distance = $details['rows'][0]['elements'][0]['distance']['value'];
print_r($distance);
?>

The above code prints 361714

Comments