2013-11-28 155 views
0

創建多維JSON我有一個PostgreSQL數據庫的表信息,如:從select語句

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中?

+3

是的。將數據存儲在數組中,然後應用'json_encode' – kero

回答

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);