【问题标题】:I need to obtain the key string from JSON我需要从 JSON 获取密钥字符串
【发布时间】:2020-11-20 17:39:40
【问题描述】:

我在请求 laravel API 中有这个 JSON:

{
  "questionary": {

    "directLeader": {
      "answer": "ALWAYS",
      "comments": "asdf"
    }
  },
  "id": 14 
}

我需要获取字符串“directLeader”,因为这个键在请求中发生了变化,我用它作为查询更新的参考。

【问题讨论】:

    标签: php json laravel request


    【解决方案1】:

    你需要json_decode()你喜欢的json

    $json = '{
      "questionary": {
    
        "directLeader": {
          "answer": "ALWAYS",
          "comments": "asdf"
        }
      },
      "id": 14 
    }';
    
    $encoded_json = json_decode($json, true);
    
    dd($encoded_json['questionary']['directLeader']);
    

    注意 json_decode() 中的 true 会将对象转换为数组,没有 true 它将是一个对象

    【讨论】:

      【解决方案2】:
      • 将 json 转换为数组:

      $array = json_decode($json, true);

      • 获取关联数组中的第一个键:

      $firstKey = array_key_first($array['questionary']);

      $firstKey 将包含您的动态密钥。

      【讨论】:

        猜你喜欢
        • 2021-09-01
        • 2022-09-29
        • 1970-01-01
        • 1970-01-01
        • 2021-02-08
        • 2013-06-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多