background image

代码如下

:

object(stdClass)#1 (5) {

    

["a"] => int(1)

    

["b"] => int(2)

    

["c"] => int(3)

    

["d"] => int(4)

    

["e"] => int(5) 

}

如果想要强制生成

PHP 关联数组,json_decode()需要加一个参数 true:

$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json),true); 

结果就生成了一个关联数组:

代码如下

:

array(5) {

  

   ["a"] => int(1)

  

   ["b"] => int(2)

  

   ["c"] => int(3)

  

   ["d"] => int(4)

  

   ["e"] => int(5)

}

5、json_decode()的常见错误
下面三种

json 写法都是错的,你能看出错在哪里吗?

代码如下

:

$bad_json = "{ 'bar': 'baz' }";

$bad_json = '{ bar: "baz" }';
$bad_json = '{ "bar": "baz", }';

对这三个字符串执行

json_decode()都将返回 null

 

,并且报错。

第一个的错误是,

json 的分隔符(delimiter)只允许使用双引号,不能使用单引号。第

二个的错误是,

json 名值对的"名"(冒号左边的部分),任何情况下都必须使用双引号。第

三个的错误是,最后一个值之后不能添加逗号(

trailing comma)。

另外,

json 只能用来表示对象(object)和数组(array),如果对一个字符串或数值使

json_decode(),将会返回 null。

var_dump(json_decode("Hello World")); //null