user3103915 user3103915 - 3 months ago 15
JSON Question

Result set of laravel data in proper format

i am using laravel to make an API that queries a database and show a simple output. Now my query goes like this:

$name = new TableName() ; //An object which is storing tablename
$result=DB::table($name->getMyTableName()) // Getting the tablename
->select()
->where('id','=',1)->orWhere('id','=',2)
->get();


Now this will fetch two records with id 1 and 2 and when I pass them through my controller, the json out put comes like this:

[
{
"id": "1",
"question": "This is",
"question_main": "sample1",
"option_1": "opt_1",
"option_2": "opt_1",
"option_3": "opt_1",
"option_4": "opt_1",
},
{
"id": "2",
"question": "This is",
"question_main": "sample2",
"option_1": "opt_1",
"option_2": "opt_2",
"option_3": "opt_3",
"option_4": "opt_4",

}
]


Now what I want is instead of option, i have something like this:

option :

{
1=>"opt_1",
2=>"opt_2",
3=>"opt_3",
4=>"opt_4",
}


Now what i tried is this:

foreach ($result as $results)
{
$final_result= array_add($final_result, 'id', $results->id);
$final_result= array_add($final_result, 'question', $results->question);
$final_result= array_add($final_result, 'question_main', $results->question_main);
$final_result= array_add($final_result, 'options', array(
[
1 => $results->option_1,
2 => $results->option_2,
3 => $results->option_3,
4 => $results->option_4,
]
));

}
return json_encode($final_result,JSON_PRETTY_PRINT);


This pretty much solves the problem however as you might have figured out key-value pair can have unique key so it will just store id=2 (the latter). I am pretty much confused on what to follow. I tried Multi dimensional array but i think i couldn't get the concept right on that.Any suggestions, thanks in advance

Answer

You can do the following using the key in your foreach:

$final_result = [];
foreach ($result as $key => $results)
{
    $final_result[$key] = [
        'id' => $results->id,
        'question' => $results->question,
        'question_main' => $results->question_main,
        'options' => [
            1 => $results->option_1,
            2 => $results->option_2,
            3 => $results->option_3,
            4 => $results->option_4
        ]
    ];

}
return json_encode($final_result,JSON_PRETTY_PRINT);