0

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
  • The "rows" and "elements" are defined as array in json, so you have to access via array index: $distance_data = json_decode($output, true); $distance_data['rows'][0]['elements'][0]['duration']['value']. Note: if you don't pass true as 2nd paramater to json_decode, the result will be stdObject instead of array. Commented May 16, 2018 at 2:53

1 Answer 1

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;
answered May 16, 2018 at 2:38
1
  • Thanks! Excellent explanation that'll help me next time. Commented May 16, 2018 at 2:48

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.