Return Json in Array instead of Object

2

I have an api that returns the data of 1 user, but it returns an object:

[{"id":"0","nome":"xx","sobrenome":"xx","email":"x","senha":"xxx","unidadexlocal":"Praia da Costa","unidadecurricular":"2","diapreparacao":"1","liberadoexercicio":"0"}]

But since it is just a user, I wanted to return the array directly:

{"id":"0","nome":"xx","sobrenome":"xx","email":"x","senha":"xxx","unidadexlocal":"Praia da Costa","unidadecurricular":"2","diapreparacao":"1","liberadoexercicio":"0"}

So I do not need to treat this as a list in android, I'm currently having to do this: user.get(0).setnome I want to do this: user.setnome

Route with slimframwork in php:

    $app->get('/aluno',function(Request $request,Response $response){
    $usermail = $request->getHeader('PHP_AUTH_USER');
    $senha = $request->getHeader('PHP_AUTH_PW');

    $sql = new Sql();
    $user =  new Usuario();
    $autenticado = $user->login($usermail[0],$senha[0]);

    if ($autenticado) {
        $resultado = $sql->select("SELECT * FROM tb_alunos WHERE email = :EMAIL LIMIT 1",array(
            ":EMAIL"=>$usermail[0]
        ));
        $response = json_encode($resultado);
        return $response;
    }else{
        return $response->withStatus(401);
    }
});
    
asked by anonymous 20.12.2017 / 20:03

1 answer

1

If you can not change the select() method to return an array without the zero index, this happens when the fetchAll() method is used, the solution is to change it to fetch()

Another way is through the array_shift() function that removes and extracts the first element of the array past.

Optionally if you are using php5.6 you can use the ... operator to unpack the direct zero index at json_encode() .

echo json_encode(...$arr);

Output:

{"id":1,"name":"fulano","email":"[email protected]"}

Example - ideone

Let's say that the array returns by select() is:

Array
(
    [0] => Array
        (
            [id] => 1
            [name] => fulano
            [email] => [email protected]
        )

)

Example with array_shift()

$extraido = array_shift($arr);
echo "<pre>";
print_r($extraido);

Output:

Array
(
    [id] => 1
    [name] => fulano
    [email] => [email protected]
)
    
20.12.2017 / 20:45