I have a mysqli query that I want to convert to json.
tried:
$myArray = array();
while ($row = mysqli_fetch_array($result)) {
$myArray[] = $row;
}
$ot = json_encode($myArray);
print_r($ot);
but got no results (blank line). If I print_r $myArray, there are values.
I can print out correct values on the while loop, so made another array and tried to add them, but neither of the following worked:
$mA []=array (alumnoX => $al1, grupox=> "two");
$mA []=array (alumnoX => (string)$al1, grupox=> "two");
$mA []=array (alumnoX => strval($al1), grupox=> "two");
$mA []=array (alumnoX => $row['alumno'], grupox=> "two");
How can I fix this?
edit -- (print_r of $myArray)
Array (
[0] => Array (
[0] => Martín
[alumno] => Martín
[1] => 1A
[grupo] => 1A
[2] => Computación básica
[materia] => Computación básica
[3] => sala cómputo cs 01
[salon] => sala cómputo cs 01
)
[1] => Array (
[0] => Martín
[alumno] => Martín
[1] => 1A
[grupo] => 1A
[2] => Introducción a la música
[materia] => Introducción a la música
[3] => Auditorio [salon] => Auditorio
)
)
When using mysqli_fetch_array()
will return an associative array and a numerically indexed array, which will duplicate all columns and confuse you and the json object. So use either mysqli_fetch_array($result,MYSQLI_ASSOC)
or mysqli_fetch_assoc($result)
so you only get the more useful associative array returned.
// assume you have code something like this
$result = mysql_query($con, $sql);
if ( ! $result ) {
echo mysqli_error($con);
exit;
}
$myArray = array();
//while ($row = mysqli_fetch_array($result)) {
while ($row = mysqli_fetch_assoc($result)) {
$myArray[] = $row;
}
$ot = json_encode($myArray);
//print_r($ot); print_r() works on arrays and $ot is now a string
echo "<pre>$ot</pre>";
The data had some none conventional characters in it, after replacing:
json_encode($myArray );
to:
json_encode($myArray, JSON_UNESCAPED_UNICODE );
It worked as expected.