PHP json_encode多维关联数组 [英] PHP json_encode multidimensional associative array

查看:479
本文介绍了PHP json_encode多维关联数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经多次使用php的json_encode()函数,但是由于某些原因,我似乎在这里找不到问题...

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);
?>

我正在使用AJAX,只是console.log()-正在像这样打印输出以打印响应...

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...

现在,如果我var_dump $trows,控制台中的输出将打印数据,因此我知道我的sql语句可以正常工作...

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);

//控制台

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"
  },

问题:为什么我的php的json_encode函数不能正常工作?我之前使用过此确切的代码,并且输出很好.

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

推荐答案

尝试添加:

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

在回显JSON编码结果之前.

Before you echo your JSON encoded result.

如果编码不起作用,请尝试以下操作:

If the encoding doesn't work try the following:

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

这篇关于PHP json_encode多维关联数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆