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);
相关推荐
zyyjay 2020-11-09
xuebingnan 2020-11-05
samtrue 2020-11-22
stefan0 2020-11-22
yifangs 2020-10-13
songshijiazuaa 2020-09-24
hebiwtc 2020-09-18
天步 2020-09-17
83911535 2020-11-13
whatsyourname 2020-11-13
zhouyuqi 2020-11-10
Noneyes 2020-11-10
mathchao 2020-10-28
王志龙 2020-10-28
wwwsurfphpseocom 2020-10-28
diskingchuan 2020-10-23
savorTheFlavor 2020-10-23