检查键是否存在于面向对象的编程中



来自Google API查询的数据有时会丢失(例如,当输入无效地址时),当发生这种情况时,未知密钥的丑陋错误。为了避免丑陋的错误,我将呼叫包裹在有条件的情况下,但似乎无法完全工作,因为我的面向对象的编程技能不存在。下面是我所拥有的,还有一些言论的尝试,所以我做错了什么?我真的只在乎 $ dataset->结果[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;

您应该知道,地理编码API Web服务还返回响应中的状态。状态指示响应中是否有有效的项目或出现问题,您没有任何结果。

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

  • "确定"
  • " Zero_Results"
  • " over_daily_limit"
  • " over_query_limit"
  • " request_denied"
  • " invalid_request"
  • " unknown_error"

因此,在尝试访问$dataset->results[0]之前,请先检查$dataset->status的值。如果"确定",则可以安全地获取结果,否则可以正确处理错误代码。

代码段可能是

 $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 
 }

我希望这会有所帮助!

最新更新