0

I have the following JSON string, I'm wanting to cycle through the 'sub' items and print them out as HTML Select Options but for some reason I can't quite get hold of them.

Only used JSON a couple times before so it's probably a rookie mistake somewhere.

{
   "1":{
      "question":"How happy are you with your car?",
      "sub":[
         "Very Happy",
         "Not So Happy",
         "Unhappy",
         "Very Unhappy"
      ]
   }
}

I have the following which let's me echo out the Question Value but how would I loop through each of the 'sub' arrays? (There's only ever going to be 1 question which is why I'm storing it in a single variable)

$questionAnswer = json_decode($data->question,true);
foreach ($questionAnswer as $key => $value) {
  $question = $value['question'];
}
4
  • inside your existing loop: foreach ($value['sub'] as $sub) { echo $sub; } Commented Feb 10, 2017 at 15:37
  • @Jeff that is an answer, not a comment Commented Feb 10, 2017 at 15:41
  • @NDM yeah, I made an asnwer out of it now... seemed to simple for an answer Commented Feb 10, 2017 at 15:46
  • @Jeff nice, have an upvote Commented Feb 13, 2017 at 13:32

2 Answers 2

4

Add another loop inside the existing one:

$questionAnswer = json_decode($data->question,true);
foreach ($questionAnswer as $key => $value) {
  $question = $value['question'];

  echo $question."<br>";
  // value['sub'] contains the array of 'subs', so you can loop through that the same way
  foreach ($value['sub'] as $sub) {  // since the key will be 0,1,2 you might not need it here, so I omitted it.
      echo $sub."<br>"; 
  }
}
Sign up to request clarification or add additional context in comments.

4 Comments

Why retain the unneeded outer loop if there is only ever one question?
there is only one question in this example, but it's much likely that this was sample-data, don't you think?
OP specified "There's only ever going to be 1 question" is all. I just get wary of nested loops.
ah, you're right, I over-read that.. I'll extend my answer then!
0
foreach ($questionAnswer as $key => $value) {
  $question = $value['question'];

  foreach ($value['sub'] as $answer) {
        echo $answer;
  }
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.