如何解码 json 对象数组

Posted

技术标签:

【中文标题】如何解码 json 对象数组【英文标题】:How to decode an array of json objects 【发布时间】:2011-02-05 08:32:21 【问题描述】:

我有一个这样的 json 对象数组:

["a":"b","c":"d","e":"f"]

将其转换为 php 数组的最佳方法是什么?

json_decode 不会处理数组部分并为该字符串返回NULL

【问题讨论】:

对我来说很好。如果你使用 json_decode($arr, true) 你会得到一个关联数组。否则,你会得到一个对象数组。也许这就是您遇到的问题? 【参考方案1】:

json_decode() 确实如此。第二个参数将结果转换为数组:

var_dump(json_decode('["a":"b","c":"d","e":"f"]', true));

// gives

array(3) 
  [0]=>
  array(1) 
    ["a"]=>
    string(1) "b"
  
  [1]=>
  array(1) 
    ["c"]=>
    string(1) "d"
  
  [2]=>
  array(1) 
    ["e"]=>
    string(1) "f"
  

【讨论】:

当第二个参数为true时,“返回的对象将转换为关联数组” 我的版本(PHP 5.2.9,json 1.2.1)也能正确地将json字符串解析成数组。 是的,我的错。从页面中抓取 json 的代码存在缺陷。谢谢。【参考方案2】:
$array = '["a":"b","c":"d","e":"f"]';
print_r(json_decode($array, true));

阅读手册 - json_decode 方法的参数已明确定义: http://www.php.net/manual/en/function.json-decode.php

【讨论】:

以上是关于如何解码 json 对象数组的主要内容,如果未能解决你的问题,请参考以下文章