2014-02-12 91 views
0

PHP表的字段的數組返回我的JSON:插入JSON到Postgres的

{   
     "date" : "2014-02-06", 
     "typeDate": "local", 
     "events" : [ 
        "To get know how Sherlock survived", 
        "Find who killed the President Kennedy", 
        "Cook met" 
        ] 
     } 

我需要插入這個對象到表中的字段,它具有這樣的對象數組:

{ 
    "dates": [ 
    {   
     "date" : "2014-02-06", 
     "typeDate": "local", 
     "events" : [ 
       "Kill John Connor", 
       "Kill T-1000", 
       "Listen Moon sonata" 
       ] 
    }, 
    {   
     "date" : "2014-02-07", 
     "typeDate": "local", 
     "events" : [ 
       "Fix Enstain's theory", 
       "Take pizza" 
       ] 
     } 
    ] 
} 

如何做到這一點是正確的?試圖使用示例

INSERT INTO aa VALUES (1, 'my_json_record'); 

我得到關於json結構的錯誤。

+0

您可以發佈確切的錯誤? – blotto

回答

1

hbasically你可以在插入到數據庫之前序列化JSON對象。

$my_json_var = json_decode($my_json_record) 

這methonde需要一個JSON編碼的字符串,並將其轉換成一個PHP變量。看到http://us2.php.net/json_decode

然後構建查詢......

$sql = "INSERT INTO aa (field1, field2) VALUES (1, '$my_json_var')";