Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

smithdp1's avatar

Populating Nested Array

Hello, I have been a member since the beginning and I am pretty stubborn when it comes time to ask for help. I really need it on this one. 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.

0 likes
2 replies
Snapey's avatar
Snapey
Best Answer
Level 122

try

            "a" => $answers->map(function($a){
                 return [
                        "option" => $a->content,
                        "correct" => $a->correct,
                ];
                });

or even just

            "a" => $answers->only(['content','correct']);
1 like

Please or to participate in this conversation.