您的位置 首页 php

PHP操作JSON格式数据的技巧

1. 介绍

1.1 介绍

JSON格式数据是现如今使用极其广泛的WEB应用的数据格式,它有着结构清晰、语法简单、占用字节少等等特点。相比较早期流行的XML格式数据来讲,JSON格式数据有着更加轻便、可读性更好、解析速度更快等等优势。

PHP语言操作JSON格式数据是有着先天优势的,因为PHP是弱类型语言,加上PHP自身的数组和JSON格式数据有着基本一致的数据结构,所以PHP操作JSON格式数据非常的简单、方便、快捷。

2. JSON

JSON格式数据除了基本数据类型整型、浮点、字符串、布尔之外,还有两个特殊的集合型类型,它们就是数组(Array)和字典(Dictionary),下面福哥将分别给大家介绍一下。

2.1 字典

所谓的字典类型就是结构内的数据是以Key-Value的方式成对的存储的,通过Key可以快速地得到对应的Value,一个字典结构内Key不能重复。

 {
  "id": 35,
  "name": "鬼谷子叔叔",
  "url": "#34;
}  

2.2 数组

数组就是用来存储多个数据的集合,数组内的元素之间没有任何关系,数组内的元素以顺序的整型数字作为键,通过键可以快速地得到对应的元素。

 [
  "PHP",
  "Python",
  "Java",
  "JavaScript",
  "C/C++",
  "Asp.net"
]  

3. 数组与JSON

在PHP语言里面数组转换JSON格式数据是通过json_encode函数完成的,PHP的数组转换到JSON格式数据会根据数组内的元素的键是否满足顺序整型数字的条件判断,如果满足就会转换成JSON的数组,如果不满足就会转换成JSON的字典。

3.1 直接转换

如果直接通过json_encode转换的话,汉字部分会被转换成unicode码。

 $jsonData = json_encode(array(
    "id"=>35,
    "name"=>"鬼谷子叔叔",
    "url"=>"#34;
));
echo $jsonData. "<br />";
$jsonData = json_encode(array(
    "PHP",
    "Python",
    "Java",
    "JavaScript",
    "C/C++",
    "Asp.net"
));
echo $jsonData. "<br />";  
PHP操作JSON格式数据的技巧

3.2 转换显示汉字

如果想要保留汉字内容,不转换成unicode码,需要使用如下的方式进行转换。

 $jsonData = json_encode(array(
    "id"=>35,
    "name"=>"鬼谷子叔叔",
    "url"=>"#34;
), JSON_UNESCAPED_UNICODE);
echo $jsonData. "<br />";
$jsonData = json_encode(array(
    "PHP",
    "Python",
    "Java",
    "JavaScript",
    "C/C++",
    "Asp.net"
), JSON_UNESCAPED_UNICODE);
echo $jsonData. "<br />";  
PHP操作JSON格式数据的技巧

4. 对象与JSON

在PHP语言里面对象转换JSON格式数据也是通过json_encode函数完成的,PHP的对象转换到JSON格式数据一定会转换成字典类型的。

4.1 直接转换

如果直接通过json_encode转换的话,汉字部分会被转换成unicode码。

 class user{
    public $id;
    public $name;
    public $url;
}

class APIController extends SystemAPIController{
    protected function user_process(){
        $user = new user();
        $user->id = 35;
        $user->name = "鬼谷子叔叔";
        $user->url = "#34;;
        $jsonData = json_encode($user);
        var_dump($jsonData);
    }
}  
PHP操作JSON格式数据的技巧

4.2 转换显示汉字

如果想要保留汉字内容,不转换成unicode码,需要使用如下的方式进行转换。

 class user{
    public $id;
    public $name;
    public $url;
}

class APIController extends SystemAPIController{
    protected function user_process(){
        $user = new user();
        $user->id = 35;
        $user->name = "鬼谷子叔叔";
        $user->url = "#34;;
        $jsonData = json_encode($user, JSON_UNESCAPED_UNICODE);
        var_dump($jsonData);
    }
}  
PHP操作JSON格式数据的技巧

5. 编码与解码

5.1 编码

所谓JSON编码就是将其他类型的数据转换成JSON格式数据的过程,因为JSON格式其实就是一个含有特殊格式的字符串,所以JSON编码就是将各种其他类型的数据转成可逆的字符串的过程。

PHP实现编码的方式就是通过内建的json_encode方法完成的,很可惜的是,这个方法对含有中文的源数据仅仅支持UTF-8的编码,如果源数据包含中文且不是UTF-8的编码就会编码失败返回false。

 $jsonData = json_encode(array(
    "id"=>35,
    "name"=>"鬼谷子叔叔",
    "url"=>"#34;
), JSON_UNESCAPED_UNICODE);
echo "<h3>JSON格式</h3>";
var_dump($jsonData);  
PHP操作JSON格式数据的技巧

5.2 解码

所谓JSON解码就是将JSON格式数据还原成原来的数据类型的过程,因为JSON格式数据其实就是一个含有特殊格式的字符串,所以JSON解码就是将JSON格式的字符串还原成原来的数据的过程。

PHP实现解码的方式就是通过内建的json_decode方法完成的,不过默认json_decode会将字典还原成stdClass对象而不是array数组,如果要把stdClass也转换成array数组的话就需要一个特殊的处理才行。

 $jsonData = "{"id":35,"name":"鬼谷子叔叔","url":"https://tongfu.net/home/35.html"}";
$orgData = json_decode($jsonData);
echo "<h3>直接还原</h3>";
var_dump($orgData);
$orgData = json_decode($jsonData, true);
echo "<h3>还原stdClass转array</h3>";
var_dump($orgData);  
PHP操作JSON格式数据的技巧

6. 总结

今天福哥带着童鞋们针对PHP操作JSON格式数据的技巧系统地讲解了一番,相信大家都应该听明白了!会操作JSON格式数据了就可以使用PHP开发程序接口了,也可以使用PHP开发前后端分离的项目了。

下一课福哥会给大家讲解Python操作JSON格式数据的技巧,敬请期待~~

文章来源:智云一二三科技

文章标题:PHP操作JSON格式数据的技巧

文章地址:https://www.zhihuclub.com/76967.shtml

关于作者: 智云科技

热门文章

评论已关闭

28条评论

  1. Get the impression if cancer has already struck you must go down this route if your ovaries are still functioning, ie not through the menopause

  2. 10, 353, 354 Age has been addressed in several studies, and the evidence for this as being a definitive risk factor for the development of BCRL remains conflicting

  3. xeloda para que sirve ciprofloxacino de 500 mg If you want to understand whether there s a positive or anegative outlook for equities, then PMIs are quite a goodmeasure

  4. However, this did not affect Zhao Lingmai is own victory, the big deal was to hand in Ye Yunhan and the others to make a bet for him

  5. Other authors show that, compared with breast and ovarian screening, the average gain in life expectancy for 30 year old carriers in the high and medium risk categories was 11

  6. There are several considerations that must be further investigated in order to maximize the benefits of local drug therapy

  7. Current guidelines have limited applicability to patients with comorbid conditions a systematic analysis of evidence based guidelines Cellular senescence requires CDK5 repression of Rac1 activity

  8. Some of us, like purple, and myself, had periods and were pregnant all along so it is not always a done deal that AF shows and you re not preggo

  9. Primary care nurses and GPs are among those who should be given precise and regular information on a patient s treatment, potential side effects and drug interactions, where to get advice, where patients should report to and how they should be managed in the event of treatment complications, such as the following 3, 7

  10. Rodolfo, USA 2022 05 29 04 21 36 Subsequent reports further argued a link between IDU and transmission of methicillin resistant S

  11. Yet, there are more complex processes at work than simply intervention or not Finally my hair dresser asked what was going on because I had lost at least 50 of the volume of my hair and it was extremely dry and brittle

  12. Pediatr Res 2007 Aug; 62 2 145 50 Lee et al L arginine supplementation reduces cardiac noradrenergic neurotransmission in spontaneously hypertensive rats

  13. 0, vet said his heart and liver is inlarged and fluid on his lungs, wants to see him in 10 days to recheck everything

  14. 1 shows a synthesis route to trans- clomiphene The highest reported accidental overdose of pregabalin capsules during the clinical development program was 8000 mg, and there were no notable clinical consequences

  15. Fatty liver index FLI and prediction of new cases of non alcoholic fatty liver disease A population based study of northern Iran

  16. Unfortunately, several other agents that in theory should ameliorate hemolytic uremic syndrome have failed to do so in clinical trials

  17. What are the possible side effects of Metrogel Vaginal Chlorambucil has a different dose than cyclophosphamide see the protocol you are using is an alkylating agent that may be substituted for cyclophosphamide

  18. Taking these antibiotics along with caffeine can increase the risk of side effects including jitteriness, headache, increased heart rate, and other side effects Bohonowych JE, Denison MS

  19. Subjects in arm A received a single dose of CYP substrates tolbutamide, chlorzoxazone, metoprolol followed by a 48 h PK assessment period

  20. What is the association between loop diuretics and clinical outcomes in patients with heart failure HF

  21. The setting conditions for this study were standardized using a frequency at 3 9 MHz, a pulse repetition frequency at 0

网站地图