user1190132 user1190132 - 6 months ago 10
JSON Question

Getting 2nd level of JSON data in PHP

I have JSON data which follows this model:

{
"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:

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 :)

Answer

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>';
}