2

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

0

1 Answer 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>';
}
Sign up to request clarification or add additional context in comments.

1 Comment

Fantastic, thank you so much Wayne, this works a treat. I tried doing a foreach inside a foreach as well and that wasn't the way to do it. What you did makes total sense. Cheers,

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.