I try to add a row of mysql query into JSON whit php. I use this code:
public function lugaresCercanos($lng, $lat, $distance){
$result=mysql_query("SELECT nombre, distancia FROM Lugar ORDER BY distancia ASC");
$info=array();
while($row = mysql_fetch_array($result,MYSQL_ASSOC)){
array_push($info,$row);
}
return json_encode($info);
This returns a JSONObject, but I'm not sure.
class resultado_final {
public $logstatus = "";
public $lugares_cercanos = "";}
$result_final = new resultado_final();
if($db->login($usuario,$passw)){
$result_final->logstatus = "0";}else{
$result_final->logstatus = "1";}
$result_final->lugares_cercanos = $lista;
echo json_encode($result_final);
This code print this:
{"logstatus":"1","lugares_cercanos":"[{\"nombre\":\"Rio Amazonas\",\"distancia\":\"5119.000\"},{\"nombre\":\"Swissotel \",\"distancia\":\"5823.000\"},{\"nombre\":\"Laguna de Yaguarcocha\",\"distancia\":\"71797.000\"}]"}
why the rows of the query are separated by backslashes? how remove the backslashes? Thanks alot!
Those backslashes are escape characters. They are escaping the special characters inside of the string associated with JSON response. You have to use JSON. parse to parse that JSON string into a JSON object.
JSON escapes the forward slash, so a hash {a: "a/b/c"} is serialized as {"a":"a\/b\/c"} instead of {"a":"a/b/c"} .
The \ is to escape the quotes (") that are part of the response.
Use stripslashes()
to strip these out.
When a string wrapped in quotes contains quotes, they have to be escaped. The escape character in php is \
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With