使用php的mysql到json。嵌套对象

时间:2011-11-06 22:12:41

标签: php javascript mysql json rest

下午好, 我试图将这些结果导入PHP中的数组,以便我可以将它们编码为json对象并将它们发送到客户端。查询结果如下所示:

   id   name    hours   cat status
3bf JFK Int 24  pass    open
3bf JFK Int 24  std closed
3bf JFK Int 24  exp open
5t6 Ohm CA  18  pass    closed
5t6 Ohm CA  18  std closed
5t6 Ohm CA  18  std2    open
5t6 Ohm CA  18  exp open
...

我希望json对象看起来像这样:

{ "id": "3bf", "name": "JFK Int", "cats":
    { [ { "cat": "pass", "status": "open" },
        { "cat": "std", "status": "closed" },
        { "cat": "exp", "status": "open" } ] }
{ "id": "5t6", "name": "Ohm CA", "cats":
    { [ { "cat": "pass", "status": "closed" },
        { "cat": "std", "status": "closed" },
        { "cat": "std2", "status": "open" } ],
        { "cat": "exp", "status": "open" } ] }

我已成功连接到mysql并使用平面表使用json_encode导出,但这部分我不知道如何在PHP中执行。感谢。

这是我的代码。这将返回一个json对象数组,但它是平的,而不是嵌套的:

$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";

$result = mysql_query($SQL);

$arr = array();
    while ($row = mysql_fetch_assoc($result)) {
        $arr[] = $row;}

$json = json_encode($arr);

echo $json;

数据本身来自将端口和猫组合在一起的视图。

1 个答案:

答案 0 :(得分:9)

你能做什么(对不起,不是我能写的最好的代码......时间短,想法和能量;-)是这样的(我希望它仍然传达了这一点):

$SQL = "SELECT id, name, hours, cat, status FROM bwt.vewPortCats";

$result = mysql_query($SQL);

$arr = array();
    while ($row = mysql_fetch_assoc($result)) {

        // You're going to overwrite these at each iteration, but who cares ;-)
        $arr[$row['id']]['id'] = $row['id'];
        $arr[$row['id']]['name'] = $row['name'];

        // You add the new category
        $temp = array('cat' => $row['cat'], 'status' => $row['status']);

        // New cat is ADDED
        $arr[$row['id']]['cats'][] = $temp;
    }


$base_out = array();

// Kind of dirty, but doesn't hurt much with low number of records
foreach ($arr as $key => $record) {
    // IDs were necessary before, to keep track of ports (by id), 
    // but they bother json now, so we do...
    $base_out[] = $record;
}

$json = json_encode($base_out);

echo $json;

没有时间对它进行测试或三思而后行,但同样,我希望它传达了这个想法......