drti52047 2014-03-27 21:56
浏览 56
已采纳

如何使用PHP将MySQL表转换为JSON?

How do I convert this:

MySQL table

Into a valid JSON file using PHP?

I tried:

$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]}";

That returns:

{'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]}

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

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

EDIT: I also tried:

$sql="SELECT ....";

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

$registos= json_encode($rows);

echo $registos;

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"
    }
]
  • 写回答

1条回答 默认 最新

  • dsw1608 2014-03-27 22:09
    关注

    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)

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#MATLAB#的问题,如何解决?(相关搜索:信噪比,系统容量)
  • ¥500 52810做蓝牙接受端
  • ¥15 基于PLC的三轴机械手程序
  • ¥15 多址通信方式的抗噪声性能和系统容量对比
  • ¥15 winform的chart曲线生成时有凸起
  • ¥15 msix packaging tool打包问题
  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作