从mysql表中获取值并转换为json对象

时间:2014-01-18 18:43:44

标签: php json

我目前正在通过foreach循环从mysql数据库中获取值。然后我将值放在数组中并将最终结果转换为json对象。但是我很难以正确的json格式获取值以便与第三方api一起使用。我怎样才能以下面显示的格式获得这些值?

所需格式:

[{education_level: "education_level", elementary: 3, middle_school: 4}]

当前格式:

{"education":"education","0":{"elementary":3},"1":{"middle_school":4}}

生成json对象

header("Content-type: application/json");
//get the course list
$education_query = $db_con->prepare("SELECT a.type, COUNT(1) AS cnt
FROM academy a
GROUP BY a.type");
$education_query->execute();
$data = $education_query->fetchAll();
$output = array('education'=>'education');
foreach ($data as $row) {
    array_push($output, array($row["type"]=>intval($row["cnt"])));
}// foreach ($data as $row) {
echo json_encode($output);

1 个答案:

答案 0 :(得分:1)

您是否尝试将输出放在另一个不是键值对的空数组中。

echo json_encode(array($output));