background image

 

输出结果是
  {"public_ex":"this is public"} 
可以看到,除了公开变量(

public

 

),其他东西(常量、私有变量、方法等等)都遗失了。

 
四、json_decode() 
 
该函数用于将 json 文本转换为相应的 PHP

 

数据结构。下面是一个例子:

代码如下:
 
  

$json

 = '{"foo": 12345}'; 

  

$obj

 = json_decode(

$json

); 

  

print

 

$obj

->{'foo'}; 

// 12345 

 
通常情况下,json_decode()总是返回一个 PHP

 

对象,而不是数组。比如:

  

$json

 = '{"a":1,"b":2,"c":3,"d":4,"e":5}'; 

  var_dump(json_decode(

$json

)); 

结果就是生成一个 PHP

 

对象:

代码如下:
 
  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) 
  } 
 
 
五、json_decode()

 

的常见错误