I have a problem returning the results I want in JSON. I make a query to the database and when I retrieve that response, I save it in an array and so on up to three times, that is, I want it to return a JSON with three rows. My problem is that it creates a double array when doing a json_encode
.
I am using Slim a PHP microframework.
My code:
$app->get('/obtenerLasTresPreguntas', function (Request $request, Response $response, $args) {
$ArrayTresPreguntas = [];
$Preguntas = Preguntas::get();
$CountPreguntas = Preguntas::count();
$array = randomGen(1,$CountPreguntas,3);
foreach ($array as &$valor) {
$Pregunta = Preguntas::where('id', '=', $valor)->get();
array_push($ArrayTresPreguntas,$Pregunta);
}
return json_encode(array_values($ArrayTresPreguntas));
});
And it returns this double array...
[
[{
"id": 5,
"pregunta": "Cosas que provocan estornudos",
"respuesta": "Polvo,Comida,Irritaci\u00f3n nariz,Mocos,Canela,Virus,Contaminaci\u00f3n,Poluci\u00f3n,Resfriado,Flores,Catarro,Invierno,\u00c1caros,Perfume fuerte,Viento,Moho,Perros,H\u00famedad,H\u00e1mster,Conejos,Fumar,Especias,Heno,Guindilla,Constipado,Alergia a los \u00e1caros,Enfermedades,Lim\u00f3n,Polen,Naranja,Fr\u00edo,Infecci\u00f3n nasal,Pluma,Gripe,Bacterias,Pinos,Pelo,Aire fr\u00edo,Animales,Rinitis,Luz,Aire,Lluvia,Agua,Tierra,Escalofr\u00edo,Reflejos,Caballos,Pimienta,Pelusas,Olor,Cebolla"
}],
[{
"id": 1,
"pregunta": "Top 10 personas m\u00e1s ricas",
"respuesta": "Amancio Ortega,Bill Gates,David Koch,Mark Zuckerberg,Warren Buffett,Carlos Slim,Charles Koch,Larry Ellison,Jeff Bezos,Bernard Arnault"
}],
[{
"id": 4,
"pregunta": "Actores principales de Harry Potter",
"respuesta": "Daniel Radcliffe,Emma Watson,Harry Mellings,Rupert Grint,Tom Felton,Oliver Phelps,Fiona Shaw,Maggie Smith,Evanna Lynch,Jason Isaacs,Devon Murray,Ralph Fiennes,Jame Phelps,Gary Oldman,David Bradley,Matthew Lewis,Richard Griffiths,Michael Gambon,Alfred Enoch,Bonnie Wright,Alan Rickman,Richard Bremmer,Richard Harris,Helena Bonham Carter,Robbie Coltrane,Robert Pattinson"
}]
]
And I want it to return exactly the same but without the previous array, which would be like this (removing the first and last brackets):
[{
"id": 5,
"pregunta": "Cosas que provocan estornudos",
"respuesta": "Polvo,Comida,Irritaci\u00f3n nariz,Mocos,Canela,Virus,Contaminaci\u00f3n,Poluci\u00f3n,Resfriado,Flores,Catarro,Invierno,\u00c1caros,Perfume fuerte,Viento,Moho,Perros,H\u00famedad,H\u00e1mster,Conejos,Fumar,Especias,Heno,Guindilla,Constipado,Alergia a los \u00e1caros,Enfermedades,Lim\u00f3n,Polen,Naranja,Fr\u00edo,Infecci\u00f3n nasal,Pluma,Gripe,Bacterias,Pinos,Pelo,Aire fr\u00edo,Animales,Rinitis,Luz,Aire,Lluvia,Agua,Tierra,Escalofr\u00edo,Reflejos,Caballos,Pimienta,Pelusas,Olor,Cebolla"
}], [{
"id": 1,
"pregunta": "Top 10 personas m\u00e1s ricas",
"respuesta": "Amancio Ortega,Bill Gates,David Koch,Mark Zuckerberg,Warren Buffett,Carlos Slim,Charles Koch,Larry Ellison,Jeff Bezos,Bernard Arnault"
}], [{
"id": 4,
"pregunta": "Actores principales de Harry Potter",
"respuesta": "Daniel Radcliffe,Emma Watson,Harry Mellings,Rupert Grint,Tom Felton,Oliver Phelps,Fiona Shaw,Maggie Smith,Evanna Lynch,Jason Isaacs,Devon Murray,Ralph Fiennes,Jame Phelps,Gary Oldman,David Bradley,Matthew Lewis,Richard Griffiths,Michael Gambon,Alfred Enoch,Bonnie Wright,Alan Rickman,Richard Bremmer,Richard Harris,Helena Bonham Carter,Robbie Coltrane,Robert Pattinson"
}]
What you say you want in the question doesn't make sense and is wrong because it wouldn't be valid JSON. What you have to do is not remove the outer brackets but the inner ones so that it remains as an array of objects (eg
[ {...}, {...}, {...} ]
) that would be valid JSON and would make more sense from a functional point of view.The double array is because it
Preguntas::where('id', '=', $valor)->get();
returns an array with objects and not a single object (as incorrectly assumed in the code). So that's why when you dojson_encode
you are left with an array ($ArrayTresPreguntas
) of arrays ($Pregunta
). So you get a structure like this:[ [{...}], [{...}], [{...}] ]
.The solution would be to keep the first value of the array
$Pregunta
(which from the looks of it only has one question anyway). For that, you would only have to change the following line of code, from:a
And that way, instead of adding an array to
ArrayTresPreguntas
, you'll add just the first element. And the final structure afterjson_encode
will look like this:that it is valid JSON (you can check it in JSONLint ) and that it is probably the structure you are really looking for instead of the one you put in the question.