JSON PHP中,Json字符串反序列化成对象/数组的方法

如下所示:

<?php
//php反编码解析json信息
//json_decode(json字符串);
$city = array('shandong'=>'jinan','henan'=>'zhengzhou','hebei'=>'shijiazhuang');
$jn_city = json_encode($city);
//反编码json
$fan_city = json_decode($jn_city,false);//第二个参数false则返回object类型,false可以默认不写
var_dump($fan_city);//object(stdClass)#1 (3) { ["shandong"]=> string(5) "jinan" ["henan"]=> string(9) "zhengzhou" ["hebei"]=> string(12) "shijiazhuang" } 
echo "<br />";
$fan_city = json_decode($jn_city,true);//第二个参数true则返回array类型
var_dump($fan_city);//array(3) { ["shandong"]=> string(5) "jinan" ["henan"]=> string(9) "zhengzhou" ["hebei"]=> string(12) "shijiazhuang" }

手动写的JSON字符串一定要用单引号才能成功反序列化成对象/数组:

<?php 
 
//json信息反编码 
 
//不同php版本,对“纯json字符串”解析存在问题 
//使用双引号定义的json字符串反编码操作变为null 
//$jn = "{'name':'tom','age':'20','addr':'beijing'}"; 
//$fan_jn = json_decode($jn,true); 
//var_dump($fan_jn);//NULL 
 
//使用单引号定义的json字符串反编码操作会成功 
$jn = '{"name":"tom","age":"20","addr":"beijing"}'; 
$fan_jn = json_decode($jn,true); 
var_dump($fan_jn);

相关推荐