我在 PHP 中有一个 MySQL 查询,它拉回两列结果
第一列是标签第二列是值
我已阅读http://nitschinger.at/Handling-JSON-like-a-boss-in-PHP但我很难理解如何从 MySQL 在 PHP 中执行以下 JSON
[
{
key: "Cumulative Return",
values: [
{
"label": "One",
"value" : 29.765957771107
} ,
{
"label": "Two",
"value" : 0
} ,
{
"label": "Three",
"value" : 32.807804682612
} ,
{
"label": "Four",
"value" : 196.45946739256
} ,
{
"label": "Five",
"value" : 0.19434030906893
} ,
{
"label": "Six",
"value" : 98.079782601442
} ,
{
"label": "Seven",
"value" : 13.925743130903
} ,
{
"label": "Eight",
"value" : 5.1387322875705
}
]
}
]
我可以手动编写一个循环来输出原始文本以形成像上面这样的 JSON,但我真的想使用json_encode
<?php
$hostname = 'localhost'; //MySQL database
$username = 'root'; //MySQL user
$password = ''; //MySQL Password
try {
$dbh = new PDO("mysql:host=$hostname;dbname=etl", $username, $password);
$query = "select label, value from table";
$stmt = $dbh->prepare($query);
$stmt->execute();
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (!empty($result)) {
echo '[
{
key: "Cumulative Return",
values: [';
for ($row = 0; $row < count($result); $row++) {
echo "{";
echo '"label": "' . $result[$row]['Label'] . '",';
echo '"Value": ' . $result[$row]['Value'];
echo "},";
echo ' ]
}
]';
}
}
}
catch (PDOException $e) {
echo $e->getMessage();
}
?>
这可以做到吗?如果是这样怎么办?