Return Json in Array instead of object

Asked

Viewed 921 times

2

I have an api that returns data from 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"}]

However as it is only 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"}

'Cause so I don’t need to treat this as list on android, currently I’m having to do so: user.get(0).setnome I want to do like 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);
    }
});
  • do you consult with PDO? uses the fetch() or fetchAll() ?

  • Yes, with Pdo, using Fetchall()

1 answer

1


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

Another way is through the function array_shift() removing and extracting the first element from the array passed.

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

echo json_encode(...$arr);

Exit:

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

Example - ideone

Let’s say the array returns by select() be it:

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

)

Example with array_shift()

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

Exit:

Array
(
    [id] => 1
    [name] => fulano
    [email] => [email protected]
)
  • It worked thanks, there are many "methods" of those that I do not know

Browser other questions tagged

You are not signed in. Login or sign up in order to post.