简体   繁体   中英

PHP json_encode multidimensional associative array

I've used php's json_encode() function many times, but for some reason I can't seem to find the problem here...

Note: I've removed error checking for clarity purposes.

//PHP

<?php
session_start();
require 'global/query.php';
$sql = "SELECT sfl,station,latitude,longitude,address,city FROM maps";
$stmt = $pdo->prepare($sql);
$stmt->execute();
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
    $trows[] = $result;
}
echo json_encode($trows);
?>

I'm using AJAX and am just console.log() -ing the output to print the response like so...

//JS

var callback = {
    "projects": function(e){
        console.log(e.target.response);
    }
};

In the console it prints a blank line with none of the data...


Now if I var_dump the $trows the output in the console will print the data so I know my sql statement works just fine...

//PHP

var_dump($trows);

//CONSOLE

array(522) {
  [0]=>
  array(6) {
    ["sfl"]=>
    string(1) "1"
    ["station"]=>
    string(26) "COMPRESSOR STATION"
    ["latitude"]=>
    string(2) "23"
    ["longitude"]=>
    string(4) "-115"
    ["address"]=>
    string(10) "Unnamed Rd"
    ["city"]=>
    string(9) "blah"
  }
  [1]=>
  array(6) {
    ["sfl"]=>
    string(1) "2"
    ["station"]=>
    string(17) "STA TERMINAL"
    ["latitude"]=>
    string(2) "16"
    ["longitude"]=>
    string(4) "-101"
    ["address"]=>
    string(11) "15 Ranch Dr"
    ["city"]=>
    string(8) "Blah Blah"
  },

Questions: Why isn't my php's json_encode function working? I've used this exact code before and the output was fine.

Try and add:

 header("Content-type: application/json; charset=utf-8");

Before you echo your JSON encoded result.

EDIT:

If the encoding doesn't work try the following:

while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) 
{
    $trows[] = array_map('utf8_encode', $result);
}

I would see what PHP tells you:

Change

echo json_encode($trows);

to

$json = json_encode($trows);
$error = json_last_error();
if ($error !== JSON_ERROR_NONE) {
    echo json_last_error_msg();
} else {
    echo $json;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM