通过PHP将MySQL查询转换为JSON对象?

时间:2013-03-20 05:12:20

标签: php mysql json

我在修改PHP数组并将其转换为JSON对象时遇到问题。数组通过MySQL查询形成。

所需的JSON格式如下:

[{
    "id":101,
    "text":"Bank / Kas",
    "children":[{
        "id":101.1,
        "text":"Bank",
        "children":[{
            "id":101.11,
            "text":"Bank Bca",
            "children":[{
                "id":101.111,
                "text":"Bank Sayangan"
                }]
        },{
            "id":101.12,
            "text":"Bank BNI"
        }]
    },{
        "id":101.2,
        "text":"Kas",
        "state":"closed",
        "children":[{
            "id":101.21,
            "text":"Kas Besar"
        },{
            "id":101.22,
            "text":"Kas Kecil"
        }]
    }]
}]

1 个答案:

答案 0 :(得分:1)

您应该使用json_encode来执行此操作:

$data = $table->fetchAll();
return json_encode($data);