【问题标题】:Working with results of api in json array在 json 数组中处理 api 的结果
【发布时间】:2014-11-24 11:02:44
【问题描述】:

我正在使用 json 根据邮政编码结果处理第 3 方 api。到目前为止,我已经得到了

$json = json_decode(file_get_contents($remote_url, false, $context))

从 print_r 中提供以下结果:

stdClass Object ( [result] => stdClass Object ( [copyrightNotice] => © 2013-2014 StreetCheck. All Rights Reserved. Contains Ordnance Survey, Royal Mail, National Statistics and Land Registry data © Crown copyright and database right 2014. [postcode] => SN5 5RF [point] => stdClass Object ( [latitude] => 51.564896985 [longitude] => -1.837017086 ) [street] => Percheron Close [street2] => [locality] => Shaw [locality2] => [postTown] => Swindon [fullLocation] => Percheron Close, Shaw, Swindon, SN5 5RF [country] => England [outputArea] => E00078711 [largeUser] => [active] => 1 [ward] => stdClass Object ( [code] => E05002164 [name] => Shaw and Nine Elms ) [constituency] => stdClass Object ( [code] => E14000947 [name] => South Swindon ) [region] => stdClass Object ( [code] => E15000009 [name] => South West ) [commentary] => Percheron Close in Shaw is in the South West region of England. The postcode is within the Shaw and Nine Elms ward/electoral division, which is in the constituency of South Swindon. [urbanClassification] => Urban ) [message] => OK [success] => 1 )

上面的代码是json的结果。

如何将 postcode 的值设置为 $postcode...

我试过了:

$postcode = $json['result']['postcode'] or [0]['postcode'] 

并得到致命错误:

不能使用 stdClass 类型的对象作为数组。

请有人让我走上正确的道路。

【问题讨论】:

    标签: php json


    【解决方案1】:

    这些是标准对象而不是数组。

               $json->result->postcode
    

    【讨论】:

      【解决方案2】:

      如果要保持代码不变,请转换为 php 数组。

      //                                                                   vvvv
      $json = json_decode(file_get_contents($remote_url, false, $context), true);
      

      这应该可以解决您的问题。

      【讨论】:

        【解决方案3】:

        如果您的 API 响应导致 stdClass 类型的对象。

        所以结果是对象的形式,而不是数组的形式。

        这样读取结果:

           <?php
           $json = json_decode(file_get_contents($remote_url, false, $context));
        
           $json->result->postcode;
           ?>
        

        参考访问:http://www.academia.edu/4092169/Get_data_from_string_with_JSON_object_in_PHP

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-03-14
          • 1970-01-01
          • 2015-06-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-10-15
          相关资源
          最近更新 更多