从select语句创建多维JSON

时间:2013-11-28 21:58:58

标签: php json

我在PostgreSQL数据库中有一个表,其中包含以下信息:

COLUMN_ID   COLUMN_TITLE                    OPTION_ID           OPTION_DESC
SZ          SIZE            S           Small
SZ          SIZE            M           Medium
SZ          SIZE            L           Large
CL          COLOR           GR          Green
CL          COLOR           WH          White
CL          COLOR           BK          Black

我想创建一个类似的JSON:

[{
    "COLUMN_ID": "SZ",
    "COLUMN_TITLE": "SIZE",
    "OPTIONS": [{
        "OPTION_ID": "S",
        "OPTION_DESC": "Small"
    }, {
        "OPTION_ID": "M",
        "OPTION_DESC": "Medium"
    }, {
        "OPTION_ID": "L",
        "OPTION_DESC": "Large"
    }]
}, {
    "COLUMN_ID": "CL",
    "COLUMN_TITLE": "COLOR",
    "OPTIONS": [{
        "OPTION_ID": "GR",
        "OPTION_DESC": "Green"
    }, {
        "OPTION_ID": "WH",
        "OPTION_DESC": "White"
    }, {
        "OPTION_ID": "BK",
        "OPTION_DESC": "Black"
    }]
}]

在PHP中有实际的方法吗?

1 个答案:

答案 0 :(得分:0)

这是我找到的解决方案。它的工作原理

 $result = pg_query($dbconn,$stmt)
          or die("Error: " . pg_last_error());

    $name_temp = '$$##';

    while ($row = pg_fetch_assoc($result)) {

            $name = $row['COLUMN_NAME'];
            $title = $row['COLUMN_TITLE'];

        if ($name != $name_temp and $name_temp != '$$##') {
            $arr[] = array('COLUMN_NAME' => $name_temp, 'COLUMN_TITLE' => $title_temp, 'OPTIONS' => $options);
            $options = '';

        }

        $options[] = array('OPTION_ID' => $row['OPTION_ID'], 'OPTION_DESC' => $row['OPTION_DESC']);
            $name_temp = $name;
            $title_temp = $title;

    }
            $arr[] = array('COLUMN_NAME' => $name_temp, 'COLUMN_TITLE' => $title_temp, 'OPTIONS' => $options);
 echo json_encode($arr);