【问题标题】:Checking If Key Exists In Object Oriented Programming检查面向对象编程中是否存在密钥
【发布时间】:2019-07-24 16:30:16
【问题描述】:

Google API 查询中的数据有时会丢失(例如输入无效地址时),当这种情况发生时,会出现未知键的丑陋错误。为了避免丑陋的错误,我将调用包装成一个条件,但似乎根本无法让它工作,因为我的面向对象编程技能不存在。以下是我所拥有的以及一些被指出的尝试,那么我做错了什么?我真的只关心 $dataset->results[0] 是否有效,之后的任何内容都会有效。

$url = "https://maps.googleapis.com/maps/api/geocode/json?address=$Address&key=$googlekey";

// Retrieve the URL contents
$c = curl_init();
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
curl_setopt($c, CURLOPT_FRESH_CONNECT, true);
curl_setopt($c, CURLOPT_URL, $url);
$jsonResponse = curl_exec($c);
curl_close($c);    

$dataset = json_decode($jsonResponse);

if (isset($dataset->results[0])) :
//if (isset($dataset->results[0]->geometry->location)) :
//if (!empty($dataset)) :
//if (!empty($dataset) && json_last_error() === 0) :
    $insertedVal = 1;
    $latitude = $dataset->results[0]->geometry->location->lat;
    $longitude = $dataset->results[0]->geometry->location->lng;
    return "$latitude,$longitude";
endif;

【问题讨论】:

    标签: php json google-maps object geocoding


    【解决方案1】:

    您应该知道 Geocoding API Web 服务也会在响应中返回一个状态。状态指示响应中是否存在有效项目或出现问题并且您没有任何结果。

    查看文档https://developers.google.com/maps/documentation/geocoding/intro#StatusCodes,您会发现有以下可能的状态

    • “确定”
    • “零结果”
    • “OVER_DAILY_LIMIT”
    • “OVER_QUERY_LIMIT”
    • “REQUEST_DENIED”
    • “INVALID_REQUEST”
    • “未知错误”

    因此,在您尝试访问$dataset->results[0] 之前,请先检查$dataset->status 的值。如果是“OK”,则可以放心的得到结果,否则正确处理错误码。

    代码 sn-p 可能是

     $dataset = json_decode($jsonResponse);
    
     if ($dataset->status == "OK") {
         if (isset($dataset->results[0])) {
             $latitude = $dataset->results[0]->geometry->location->lat;
             $longitude = $dataset->results[0]->geometry->location->lng;
         }
     } elseif ($dataset->status == "ZERO_RESULTS") {
         //TODO: process zero results response 
     } elseif ($dataset->status == "OVER_DAILY_LIMIT" {
         //TODO: process over daily quota 
     } elseif ($dataset->status == "OVER_QUERY_LIMIT" {
         //TODO: process over QPS quota  
     } elseif ($dataset->status == "REQUEST_DENIED" {
         //TODO: process request denied  
     } elseif ($dataset->status == "INVALID_REQUEST" {
         //TODO: process invalid request response  
     } elseif ($dataset->status == "UNKNOWN_ERROR" {
         //TODO: process unknown error response 
     }
    

    我希望这会有所帮助!

    【讨论】:

    • 谢谢,这正是我需要知道的,虽然您没有解决确切的问题,但您的示例显示了检查 isset($dataset->results[0]) 就像我一样这样做证实了我做对了。添加 $dataset->status == "OK" 是一个奖励,特定的错误部分也是如此。虽然我已经写了一个函数来输出错误,但我不确定它的有效性,所以你也帮忙确认了。
    猜你喜欢
    • 2014-09-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-05
    • 1970-01-01
    • 2015-06-07
    • 2018-04-20
    相关资源
    最近更新 更多