Array in PHP for JSON

2

Hello, how are you?

I'm getting the values from a table in a database and "transforming" them into JSON. I have 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);

However, it only returns me

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

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

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

How to do this?

    
asked by anonymous 24.12.2014 / 06:25

2 answers

6

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

Create a% multi-dimensional% co:

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' )
    
24.12.2014 / 06:33
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, at each iteration, the result of the query query, in the variable $return_arr , created before the loop.

    
24.12.2014 / 06:37