0

I am using Laravel 8.x and php 7.4. I am trying to return data for a javascript quiz app called 'slickQuiz' and it must be formed like this:

{ 
            "q": "What number is the letter A in the English alphabet?",
            "a": [
                {"option": "8",      "correct": false},
                {"option": "14",     "correct": false},
                {"option": "1",      "correct": true},
                {"option": "23",     "correct": false} // no comma here
            ],
            "correct": "<p><span>That's right!</span> The letter A is the first letter in the alphabet!</p>",
            "incorrect": "<p><span>Uhh no.</span> It's the first letter of the alphabet. Did you actually <em>go</em> to kindergarden?</p>" // no comma here
   },

I am trying to loop through my data in my controller like this:

foreach ($questions as $q) {
            $jsondata[] = [
            "q" => $q->content,
            "a" => [
            foreach ($q->answers as $a) {
                        "option" => $a->content,
                        "correct" => $a->correct,
            }
         ]
        ]
        }

I get this error:

ParseError
syntax error, unexpected 'foreach' (T_FOREACH), expecting ']'

Any help would be appreciated.

4
  • 1
    Try to prepare the content for "a" first outside of the jsondata append. Then use the prepared "a" within the append on $jsondata Commented Nov 2, 2021 at 18:57
  • prepare inside of foreach ($questions as $q) { Commented Nov 2, 2021 at 19:00
  • I tried and can't get it Commented Nov 2, 2021 at 19:08
  • Git it! Thank you! Commented Nov 2, 2021 at 19:17

1 Answer 1

0

I eneded up doing this from user1915746 comment:

foreach ($questions as $q) {
            foreach ($q->answers as $a) {
                $adata[] = [
                    "option" => $a->content,
                    "correct" => $a->correct,
                ];
            }
            $jsondata[] = [
                "q" => $q->content,
                "a" => $adata,

            ];
        }
Sign up to request clarification or add additional context in comments.

1 Comment

Yes, that's what I meant. Another approach is the solution described here stackoverflow.com/questions/37195486/… But in my opinion it is much less readable than your solution.

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.