I have the following code to go through a list of json... When printing the json it does it in a very messy way and even a lot of data is repeated.
It's wrong?
<?php
include_once "conexion.php";
$sql_registros = mysqli_query($conexion,"SELECT * FROM clientes ORDER BY id ASC");
while ($resultado = mysqli_fetch_array($sql_registros)) {
$json[] = $resultado;
}
echo json_encode($json,JSON_UNESCAPED_UNICODE);
?>
mysqli_fetch_array
It returns the data twice, with a numerical index and with an associative index, that is, if you have, for example, the columns:id, nombre, apellido
and you use,mysqli_fetch_array
you will have something like this for each row:You see twice
1
, twicePedro
, twiceDíaz
, etc because of what has already been said:mysqli_fetch_array()
it does two types of grouping with the results.So it is better to use a more specific method . If you are interested in associative keys (which is what is usually used in JSON), then you can put it like this:
In that case, your result will be this:
If, on the other hand, you are interested in numerical keys, you can put it like this:
And your result will be this:
In short,
mysqli_fetch_assoc()
andmysqli_fetch_row()
are more specific methods to obtain data, depending on whether we want an associative or numeric array.This issue was already covered in detail in the accepted answer of the question: json php query with duplicate results .