如何使用PHP将MySQL表转换为JSON? [英] How to convert MySQL table into JSON using PHP?

查看:130
本文介绍了如何使用PHP将MySQL表转换为JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我该如何转换:

使用PHP转换为有效的JSON文件?

Into a valid JSON file using PHP?

我尝试过:

$sql="SELECT ... more code here";

$result = $pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);

$real= implode(",",array_map(function($a) { return $a["real"]; }, $rows));
$orcamento = implode(",",array_map(function($a) { return $a["orcamento"]; }, $rows));
$desvio = implode(",",array_map(function($a) { return $a["desvio"]; }, $rows));


echo "{'name': 'orcamento', 'data': [$orcamento]},
        {'name': 'real', 'data': [$real]},
        {'name': 'desvio', 'data': [$desvio]}";

返回:

{'name': 'orcamento', 'data': [14000.00,8500.00,0.00]},
    {'name': 'real', 'data': [2038.00,120.00,15000.00]},
    {'name': 'desvio', 'data': [-11962.00,-8380.00,15000.00]}

根据JSONLint,这是无效的(而且我认为其余代码无法正常工作的原因.我得到:

Which according to JSONLint is invalid (and I think the reason why the rest of my code isn't working. I get:

Parse error on line 1:
{    'name': 'orcamento',
-----^
Expecting 'STRING', '}'

所以我的问题是:如何修复我的PHP代码以获取有效的JSON?

So my question is: How do I fix my PHP code in order to get a valid JSON?

我也尝试过:

$sql="SELECT ....";

$result = $pdo->query($sql);
$rows = $result->fetchAll(PDO::FETCH_ASSOC);

$registos= json_encode($rows);

echo $registos;

这将返回有效的JSON,但格式错误:

That returns a valid JSON, but with the wrong format:

[
    {
        "real": "2038.00",
        "orcamento": "14000.00",
        "desvio": "-11962.00"
    },
    {
        "real": "120.00",
        "orcamento": "8500.00",
        "desvio": "-8380.00"
    },
    {
        "real": "15000.00",
        "orcamento": "0.00",
        "desvio": "15000.00"
    }
]

推荐答案

为了安全起见,请像这样使用json_encode:

To be on the safe side, use json_encode like this:

$real = array_map(function($a) { return $a["real"]; }, $rows);
$orcamento = array_map(function($a) { return $a["orcamento"]; }, $rows);
$desvio = array_map(function($a) { return $a["desvio"]; }, $rows);

echo json_encode(array(
    array('name' => 'orcamento', 'data' => $orcamento),
    array('name' => 'real', 'data' => $real),
    array('name' => 'desvio', 'data' => $desvio)
));

(但本质上,在原始输出中缺少用于包围对象的[],您需要使用双引号"来引用键和字符串)

(but in essence in your original output the [ and ] to surround the objects are missing and you need to use double quotes " for quoting the keys and strings)

这篇关于如何使用PHP将MySQL表转换为JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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