Home  >  Article  >  Backend Development  >  In JSON PHP, how to deserialize Json string into object/array

In JSON PHP, how to deserialize Json string into object/array

不言
不言Original
2018-05-31 15:25:591575browse

This article mainly introduces the method of deserializing JSON strings into objects/arrays in JSON PHP. It has certain reference value. Now I share it with you. Friends in need can refer to it

is as follows:

<?php
//php反编码解析json信息
//json_decode(json字符串);
$city = array(&#39;shandong&#39;=>&#39;jinan&#39;,&#39;henan&#39;=>&#39;zhengzhou&#39;,&#39;hebei&#39;=>&#39;shijiazhuang&#39;);
$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" }

##The manually written JSON string must use single quotes. Successfully deserialized into object/array:

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

The above is the entire content of this article, thank you for reading. Please pay attention to the PHP Chinese website for more information!

The above is the detailed content of In JSON PHP, how to deserialize Json string into object/array. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn