【问题标题】:How to check if JSON index (key) exists?如何检查 JSON 索引(键)是否存在?
【发布时间】:2016-03-21 20:36:27
【问题描述】:

我有这个 API 可以返回:

{“响应”: [{"cid":5122405,"title":"Austin","area":"Estrie","re​​gion":"魁北克"},{"cid":5467453,"title":"Austin","re​​gion ":"马尼托巴"}]}

我想打印所有区域,但作为上面的示例,魁北克的奥斯汀有面积值(埃斯特里),但马尼托巴的奥斯汀没有。

我的代码是:

for($i = 0; $i < count($json_array['response']); ++$i){ 
    echo $json_array['response'][$i]['area'];

但问题是我收到此错误通知:Undefined index: area in... where area value is not present (like Austin in Manitoba).

如何检查区域是否存在?

【问题讨论】:

  • if(isset($json_array['response'][$i]['area']))
  • @Xatoo 这也可能是问题的答案
  • 那么在这种情况下它可能会被标记为重复,否则

标签: php json indexing key undefined


【解决方案1】:

有两种基本方法可以解决这个问题。

最简单的就是检查变量是否存在

echo array_key_exists('area', $json_array['response'][$i]) ? $json_array['response'][$i]['area'] : null;

另一种方法是标准化来自 API 的响应,以便 area 密钥始终存在

function standardizeApi($values) 
{
    foreach ($values['response'] as $i => $details) {
        if (!array_key_exists('area', $details)) {
            $values['response'][$i]['area'] = null; // default value
        }
    }
    return $values;
}

$json_array = standardizeApi($json_array);
// loop though as normal

如果您有多个要检查的键,则第二种方法会更好。您可以确保数组包含值,即使 api 缺少它们。

编辑:拼写

【讨论】:

    【解决方案2】:

    快速

    for($i = 0; $i < count($json_array['response']); ++$i){ 
         if($json_array['response'][$i]['area']){
    echo $json_array['response'][$i]['area'];
    
    };

    【讨论】:

      【解决方案3】:

      您可以将json解码作为一个对象并获取项目列表:

      $stringJson = '{"response":[{"cid":5122405,"title":"Austin","area":"Estrie","region":"Quebec"},{"cid":5467453,"title":"Austin","region":"Manitoba"}]}';
      $jsonObj = json_decode($stringJson);
      foreach ($jsonObj->response as $item) {
         echo $item->cid; // 5122405 5467453
      }
      

      【讨论】:

        猜你喜欢
        • 2011-01-09
        • 1970-01-01
        • 2014-01-08
        • 2021-07-22
        • 2015-08-10
        • 2013-03-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多