【问题标题】:PHP if else statement testing whether api php field is emptyPHP if else语句测试api php字段是否为空
【发布时间】:2015-01-07 23:05:50
【问题描述】:

我正在尝试从 ip geolocation api 中获取 city 属性。 api返回的示例:

{"as":"AS38484 Virgin Broadband VISP","city":"Adelaide","country":"Australia","countryCode":"AU","isp":"iseek Communications","lat":-27,"lon":133,"org":"iseek Communications","query":"1.178.0.144","region":"","regionName":"","status":"success","timezone":"","zip":""}

我的代码:

$query = '{"as":"AS38484 Virgin Broadband VISP","city":"Adelaide","country":"Australia","countryCode":"AU","isp":"iseek Communications","lat":-27,"lon":133,"org":"iseek Communications","query":"1.178.0.144","region":"","regionName":"","status":"success","timezone":"","zip":""}';
$query = @unserialize($query);
if($query && $query['status'] == 'success') {
    if(!empty($query['city'])) {
        $city =  $query['city'];
        // routine that uses $city gets called
    } else {
        $lat = $query['lat'];
        $lon = $query['lon'];
        // routine that uses $lat, $lon gets called
    }
}

基本上,if(!empty($query['city'])) 的行为不如预期(我真的不知道,上周我一直在使用 PHP)。我还尝试在 if 语句之前设置$city,然后测试if($city != '')

问题:没有找到条件组合,然后将城市属性设置为city?而当没有city属性时,它也会跳过else部分,不设置lat/lon

注意:citylat/lon 之间的区别的原因是我查询的天气 api 更喜欢 city 但不是每个 ip 都能提供一个。

谢谢

【问题讨论】:

  • 还有什么问题?
  • 代码中有分号:)。从未找到城市属性是抱歉将编辑的问题。

标签: php if-statement ip-geolocation


【解决方案1】:

$query 不是一个序列化的 PHP 数组,如果你在unserialize 调用之前没有使用'@',你会看到它。它看起来像 JSON,所以也许 json_decode 是您正在寻找的?

【讨论】:

    【解决方案2】:

    两个问题:

    1) 您需要使用json_decode 来反序列化 json 数据

    2) 由于它将反序列化为一个对象,因此您将使用

    访问这些字段
     $query->city;
    

    不是

     $query['city'];
    

    【讨论】:

      【解决方案3】:

      正如@kao3991 和@andrew 所说,您的数据是JSON 而不是序列化数组。试试这个:

      $query = '{"as":"AS38484 Virgin Broadband VISP","city":"Adelaide","country":"Australia","countryCode":"AU","isp":"iseek Communications","lat":-27,"lon":133,"org":"iseek Communications","query":"1.178.0.144","region":"","regionName":"","status":"success","timezone":"","zip":""}';
      $query = json_decode($query, true);
      if($query && $query['status'] == 'success') {
          if(!empty($query['city'])) {
              $city =  $query['city'];
              // routine that uses $city gets called
          } else {
              $lat = $query['lat'];
              $lon = $query['lon'];
              // routine that uses $lat, $lon gets called
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-07-07
        • 2014-09-14
        • 2011-05-18
        • 2015-06-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多