Slim - How to return a json in a single array (I create double array)

1

I have a problem when returning the results I want in JSON. I make a query to the database and when I rescue that answer I keep it in an array and so on up to three times, that is, I want it to return a JSON of three rows. My problem is that I create a double array by doing a json_encode .

I'm 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 he 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 that I get to return exactly the same but without the previous array, which would be this way (it is removing the first and the last bracket):

[{
    "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"
}]
    
asked by Daniel 31.03.2018 в 00:35
source

1 answer

2

What you say you want in the question does not make sense and is incorrect because it would not be valid JSON. What you have to do is not remove the brackets from outside but the internal brackets so that it remains as an array of objects (eg [ {...}, {...}, {...} ] ) that would be valid JSON and would make more sense from the functional point of view.

The double array is because Preguntas::where('id', '=', $valor)->get(); returns an array with objects and not a single object (as it is incorrectly assumed in the code). So that's why when doing json_encode you have an array ( $ArrayTresPreguntas ) of arrays ( $Pregunta ). That's why you get a structure like this: [ [{...}], [{...}], [{...}] ] .

The solution would be to keep the first value of the array $Pregunta (which seems to only have one question anyway). For that, you just have to change the following line of code, from:

array_push($ArrayTresPreguntas,$Pregunta);

a

array_push($ArrayTresPreguntas,$Pregunta[0]);

And that way, instead of adding an array to ArrayTresPreguntas , you will add only the first element. And the final structure after json_encode will look like this:

[
    {
        "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"
    }
]

that is valid JSON (you can check it in JSONLint ) and that is surely the structure you are really looking for instead of the one you put in the question.

    
answered by 31.03.2018 / 16:00
source