简体   繁体   中英

How to convert MySQL table into JSON using PHP?

How do I convert this:

MySQL表

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

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)

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