Oklas Mathew
Oklas Mathew

Reputation: 51

read arrays in google sheet json response in php

$url = 'https://sheets.googleapis.com/v4/spreadsheets/...';
$json= file_get_contents($url);
$obj = json_decode($json);
$obj = $obj->{'values'};     
print_r( $obj);

Response from google sheet is like :

{ "range": "Recipes!D10:E10", "majorDimension": "ROWS", "values": [ [ "65", "122.9" ] ] }

After i decode the response with lines of code above,it is like this :

Array ( [0] => Array ( [0] => 65 [1] => 122.9 ) )    

// How to extract the data "65" and "122.9" from this decoded response ?

Upvotes: 0

Views: 217

Answers (3)

bestprogrammerintheworld
bestprogrammerintheworld

Reputation: 5520

You have

$obj = $obj->{'values'};   

which contains:

Array ( 
    [0] => Array ( 
               [0] => 65 
               [1] => 122.9
          )   

So $obj[0] contains:

Array ( 
    [0] => 65 
    [1] => 122.9  
)  

and obviously

$obj[0][0] => 65
$obj[0][1] => 122.9

Upvotes: 0

RiggsFolly
RiggsFolly

Reputation: 94642

you simply missed a couple of array levels

$obj = json_decode($json);
$values = $obj->values[0];     

echo $values[0] . PHP_EOL;
echo $values[1];

RESULT

65
122.9

Upvotes: 1

RLoris
RLoris

Reputation: 526

If we look closely at the doc here : https://www.php.net/manual/fr/function.json-decode.php, You need to pass true for an Assoc array instance of a simple array. So you should do something like json_decode($json, true) and you should be good to go ! Then get $obj['values'][0][0] and $obj['values'][0][1]

Upvotes: 0

Related Questions