2013-02-19 50 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

相关问题