在PHP中获取第二级JSON数据

时间:2021-06-07 18:31:26

I have JSON data which follows this model:

我有遵循这个模型的JSON数据:

{
  "questions": [
    {
      "questionKey": 0,
      "question": "string",
      "required": true,
      "type": "multipleChoice",
      "maxSize": 0,
      "answers": [
        {
          "answer": "string",
          "answerKey": 0
        }
      ]
    }
  ],
  "fields": [
    {
      "field": "string",
      "answers": [
        "string"
      ],
      "required": true,
      "maxSize": 0
    }
  ]
}

I am having difficult getting all the fields > field values. When i do a var_dump($jsondata) it is printing all the data so I know I am getting and storing the data ok. I know I need to do a foreach statement like:

我很难得到所有的字段>字段值。当我做var_dump($jsondata)时,它会打印所有的数据,所以我知道我正在获取和存储数据。我知道我需要对每句话做一个解释,比如:

foreach ($jsondata as $data) { 
echo $data['fields'];
}

I know this is wrong but I don't know how to cycle through all the fields > field values. Your help is much appreciated :)

我知道这是错误的,但我不知道如何循环遍历所有字段>字段值。非常感谢您的帮助。

1 个解决方案

#1


4  

Try something like this:

试试这样:

//Decode JSON string into a PHP array.
$jsonData = json_decode($jsonStr, true);

//Loop through it like any associative array.
foreach($jsonData['fields'] as $field){
    var_dump($field);
    echo $field['field'] , '<br>';
}

#1


4  

Try something like this:

试试这样:

//Decode JSON string into a PHP array.
$jsonData = json_decode($jsonStr, true);

//Loop through it like any associative array.
foreach($jsonData['fields'] as $field){
    var_dump($field);
    echo $field['field'] , '<br>';
}