【问题标题】:read arrays in google sheet json response in php在 php 中读取 google sheet json 响应中的数组
【发布时间】:2020-06-17 20:20:23
【问题描述】:
$url = 'https://sheets.googleapis.com/v4/spreadsheets/...';
$json= file_get_contents($url);
$obj = json_decode($json);
$obj = $obj->{'values'};     
print_r( $obj);

来自谷歌表的响应如下:

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

在我用上面的代码行解码响应后,它是这样的:

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

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

【问题讨论】:

    标签: php google-sheets-api


    【解决方案1】:

    您只是错过了几个数组级别

    $obj = json_decode($json);
    $values = $obj->values[0];     
    
    echo $values[0] . PHP_EOL;
    echo $values[1];
    

    结果

    65
    122.9
    

    【讨论】:

    • 谢谢哥们的帮助!这解决了问题。非常感谢!
    【解决方案2】:

    你有

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

    其中包含:

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

    所以$obj[0] 包含:

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

    显然

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

    【讨论】:

    • 谢谢哥们的帮助!这解决了问题。非常感谢!
    • 没问题!
    【解决方案3】:

    如果我们仔细查看这里的文档:https://www.php.net/manual/fr/function.json-decode.php, 您需要为简单数组的 Assoc 数组实例传递 true。因此,您应该执行类似 json_decode($json, true) 之类的操作,并且一切顺利!然后得到 $obj['values'][0][0] 和 $obj['values'][0][1]

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-27
      • 1970-01-01
      • 2015-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多