【问题标题】:Key Exist in a complex php variable [duplicate]关键存在于复杂的php变量中[重复]
【发布时间】:2018-03-30 21:35:40
【问题描述】:

如何确保一个键存在于复杂的PHP 变量中? 以下是Google APIJSON 输出:

{
   "destination_addresses" : [
      "India"
   ],
   "origin_addresses" : [
      "India"
   ],
   "rows" : [
      {
         "elements" : [
            {
               "distance" : {
                  "text" : "86 m",
                  "value" : 86
               },
               "duration" : {
                  "text" : "1 min",
                  "value" : 24
               },
               "status" : "OK"
            }
         ]
      }
   ],
   "status" : "OK"
}

有时会变成这样:

{
   "destination_addresses" : [ "20.348326,85.8160893" ],
   "origin_addresses" : [ "20.3487083,-85.8157674" ],
   "rows" : [
      {
         "elements" : [
            {
               "status" : "ZERO_RESULTS"
            }
         ]
      }
   ],
   "status" : "OK"
}

我已使用

将此 JSON 转换为 PHP 变量
$response_a = json_decode($response, true);

现在,我如何确保仅在输出中存在键距离时才读取键距离,例如:

$dist = $response_a['rows'][0]['elements'][0]['distance']['text'];

在响应 1 的情况下;否则

$response_a['rows'][0]['elements'][0]['status'] 

【问题讨论】:

  • 为什么不先检查状态?

标签: php json google-api


【解决方案1】:

你可以使用 isset(...) 例如:

if (isset($response_a['rows'][0]['elements'][0]['distance']['text'])) {
      $dist = $response_a['rows'][0]['elements'][0]['distance']['text']; 
} else {
      $dist =1;

}  ;

【讨论】:

    猜你喜欢
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2021-09-21
    相关资源
    最近更新 更多