Getting Values from JSON Array using PHP

时间:2021-02-25 13:39:07

Here is my Request

这是我的要求

$GoogleApiResult = file_get_contents("https://maps.googleapis.com/maps/api/distancematrix/json?origins=11.0450,76.9200&destinations=11.0450,76.9455");
return $GoogleApiResult;

And my Response is

我的回答是

{ "destination_addresses" : [ "201, Koundampalayam, Coimbatore, Tamil Nadu 641030, India" ], "origin_addresses" : [ "1, Luna Plastics Road, Lakshmi Nagar, Coimbatore, Tamil Nadu 641025, India" ], "rows" : [ { "elements" : [ { "distance" : { "text" : "3.5 km", "value" : 3523 }, "duration" : { "text" : "6 mins", "value" : 382 }, "status" : "OK" } ] } ], "status" : "OK" }

How can i get the value of Distance (3.5km) and Duration (6 min) ?

如何获得距离(3.5km)和持续时间(6分钟)的值?

1 个解决方案

#1


1  

You need to convert json response to PHP array using json_decode function.

您需要使用json_decode函数将json响应转换为PHP数组。

Use below code to get duration & distance from response from api:

使用下面的代码来获取api响应的持续时间和距离:

$array=json_decode($json); //$json is api response
//var_dump($array);

echo $array->rows[0]->elements[0]->distance->text;
echo $array->rows[0]->elements[0]->duration->text;

#1


1  

You need to convert json response to PHP array using json_decode function.

您需要使用json_decode函数将json响应转换为PHP数组。

Use below code to get duration & distance from response from api:

使用下面的代码来获取api响应的持续时间和距离:

$array=json_decode($json); //$json is api response
//var_dump($array);

echo $array->rows[0]->elements[0]->distance->text;
echo $array->rows[0]->elements[0]->duration->text;