2013-02-19 39 views
0

我有以下的JSON:存儲陣列,多數民衆贊成在內側對象

"list": { 
      "list_id": "2kA", 
      "title": "Social Media", 
      "description": "Trending", 
      "image": [ 
       "http://cdn.socialmediaexaminer.com/wp-content/uploads/2012/11/br-campaign-report.png?9d7bd4", 
       "http://cdn.socialmediaexaminer.com/wp-content/uploads/2012/11/br-campaign-report.png?9d7bd" 
      ], 
      "views": 65 
     } 

我怎樣才能在數據庫中存儲的圖像陣列的序列化版本?做任何以下任何返回一個錯誤:

$images = $item->list->image; 
$images = $item->list->image->[0]; 
$images = $item->list->['image']; 

謝謝你們!

+0

無需再次序列化? JSON本身是以序列化的格式。將JSOn存儲到數據庫,並檢索時,你可以去json_decode() – 2013-02-19 06:36:37

+0

我從一個API拉它,並在數據庫緩存結果。我將在視圖端解密JSON,但這是一個簡單的cron來緩存結果。 – viablepath 2013-02-19 06:39:06

回答

1

您可以訪問到你的圖片是這樣的:

foreach($item->list->image as $your_image) { 
    //do what you want 
} 

或使用相關數組這樣

$x = json_decode('{"list": { 
      "list_id": "2kA", 
      "title": "Social Media", 
      "description": "Trending", 
      "image": [ 
       "a", 
       "b" 
      ], 
      "views": 65 
     }}', true); 

foreach($x['list']['image'] as $your_image) { 
    //do what you want 
} 

將它保存到你的數據庫使用json_encode(逃逸),作爲例子一個mysqli連接

$query = 'INSERT INTO your_table (...) 
      VALUES (\''.mysqli_real_escape_string($dblink, json_encode($your_array)).'\')'; 

關於選擇你可以使用json_decode!

+0

我想將整個「圖像」數組存儲在數據庫字段中。我已經在整個對象上使用了JSON解碼,並提取了list_id,title,description&views字段。 – viablepath 2013-02-19 06:40:27

+0

@viablepath我的編輯! – silly 2013-02-19 07:05:34

1
In your DB, data is in JSON, literally it means its a formatted string like:  
"something here...." 

You cannot access it by "->" as it is not an object. 

So, 
Convert your string(JSON) to Object to access like these: 
$x['list']['image'] 
It can be achieved by json decoding your string which will convert your string to object 

There was a bad error in code too. This one : $item->list->image->[0]; 
you cannot access an element of an array like this image->[0] --> it should be 
$item->list->image[0] 
+0

$ images = $ item-> list-> image [0];效果很好。唯一的問題是它只能拉第一個數組項目。我如何儲存ALL? – viablepath 2013-02-19 06:50:12

+0

老兄我只是說這只是集中在圖像數組上。你的代碼是$ item-> list-> image - > [0]; – 2013-02-19 06:54:51

相關問題