Nemuri Nemuri - 2 months ago 24
JSON Question

json_encode not working as expected

I have this piece of code

<?php
include_once("../modelos/conexion.php");

$database = new Database();

$conexion = $database->getConnection();


$statement = $conexion->prepare("SELECT nombre_asignatura FROM asignaturas");
$statement->execute();
$asignaturas=$statement->fetchAll(PDO::FETCH_ASSOC);

var_dump($asignaturas);

echo "<br><br><br>";

foreach ($asignaturas as $key => $value) {
echo json_encode($value);
}
echo "<br><br><br>";
foreach ($asignaturas as $key => $value) {
print_r($value);
echo "<br>";
}
?>


Which gives the following results

results

enter image description here

I cannot understand why does it work only once. Also, is there a way to use ir to encode the whole array at once? I tried to use the "depth" variable, but I don't quite get it

Answer

json_last_error() will help figuring out what is wrong: http://php.net/manual/en/function.json-last-error.php

As @user2864... pointed out I also guess it is the special characters that fail. Also as @Ghost pointed out, don't foreach encode.

json_encode($array)

In case this will fail debug with the json_last_error().