PHP array for JSON

Asked

Viewed 341 times

2

Hello, all right, all right?

I am taking the values of a table in a database and "transform" them into JSON. I am with the following PHP code:

$sql = "SELECT * FROM pessoas";
$query = mysqli_query($mysqli, $sql);

$arr = array();

while ($dados = mysqli_fetch_assoc($query)) {
    $arr['nome'] = $dados['nome'];
    $arr['sobrenome'] = $dados['sobrenome'];
}

return json_encode($arr);

But he returns to me only

{"nome":"Leo","sobrenome":"Nerone"}

But I would like him to return everything, for example:

{"nome":"Leo","sobrenome":"Nerone"},
{"nome":"Alguem","sobrenome":"Loco"}

How to do this?

2 answers

6


You are creating an array only with the last item, as the loop overwrites the previously saved item.

Create a $arr multidimensional:

while ($dados = mysqli_fetch_assoc($query)) {
    $arr[] = array( 'nome' => $dados['nome'] , 'sobrenome' => $dados['sobrenome'] );
}

your output will be an array like:

$arr[0] = array( 'nome' => 'Leo' , 'sobrenome' => 'Nerone' )
$arr[1] = array( 'nome' => 'Alguem' , 'sobrenome' => 'Loco' )
  • 1

    +1 This is the best solution and solves the problem.

3

Try this:

$return_arr = array();
while ($row = mysqli_fetch_assoc($query)) {
    $row_array['nome'] = $row['nome'];
    $row_array['sobrenome'] = $row['sobrenome'];
    array_push($return_arr,$row_array);
}
echo json_encode($return_arr);

With array_push($return_arr,$row_array); you will be stacking, with each iteration, the query result, in the variable $return_arr, created before the loop.

  • 1

    could you comment and explain the code please? so whoever asked the question could understand what you answered. You can [Dit] your answer.

Browser other questions tagged

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