Table of Contents
程序8:
Home php教程 php手册 PHP中Json使用全面解析

PHP中Json使用全面解析

Jun 13, 2016 am 09:38 AM
json php

对于JSON(JavaScript Object Notation)大家应该不陌生,它是一种轻量级的数据交换格式。易于人阅读和编写。同时也易于机器解析和生成。它基于JavaScript Programming Language, Standard ECMA-262 3rd Edition - December 1999的一个子集。JSON采用完全独立于语言的文本格式,但是也使用了类似于C语言家族的习惯(包括C, C++, C#, Java, JavaScript, Perl, Python等)。这些特性使JSON成为理想的数据交换语言。

JSON建构于两种结构:

“名称/值”对的集合(A collection of name/value pairs)。不同的语言中,它被理解为对象(object),纪录(record),结构(struct),字典(dictionary),哈希表(hash table),有键列表(keyed list),或者关联数组 (associative array)。 值的有序列表(An ordered list of values)。在大部分语言中,它被理解为数组(array)。

PHP的serialize是将变量序列化,返回一个具有变量类型和结构的字符串表达式,说起来两者都是以一种字符串的方式来体现一种数据结构,那它们之间有什么区别呢。

先从JSON说起,看一个简单的实例。

程序1:

var test = {"Name":"Peter","Age":20};
document.write(test.Name + ": " + test.Age);
Copy after login

显示结果:

Peter: 20
Copy after login

变量test中{"Name":"Peter","Age":20}为一个有2个元素的对象(感觉就像PHP的数组):Name为Peter,Age为20。

当然也可以变得复杂些:

程序2:

var test = {"User":{"Name":"Peter","Age":20},"Company":"FORD"};
document.write(test.User.Name + ": " + test.Company);
Copy after login

显示结果:

Peter: FORD
Copy after login

这个例子中User元素中包含了Name和Age。

如果要体现多个User,则需要使用数组,区别于对象的"{}",数组使用"[]"。

程序3:

var test = [
                 {"User":{"Name":"Peter","Age":20},"Company":"FORD"},
                 {"User":{"Name":"Li Ming","Age":20},"Company":"Benz"}
			];
document.write(test[1].User.Name + ": " + test[1].Company);
//或者使用:document.write(test[1]["User"]["Name"] + ": " + test[1]["Company"]);
Copy after login

显示结果:

Li Ming: Benz
Copy after login

通过以上简单实例就能将一些复杂数据通过一个字符串来进行传递,再配合上Ajax的确是方便很多。

下面再来看看PHP的serialize函数的作用。

程序4:

$arr = array
       (
          'Peter'=> array
          (
            'Country'=>'USA',
            'Age'=>20
          ),
          'Li Ming'=> array
          (
             'Country'=>'CHINA',
             'Age'=>21
          )
        );
$serialize_var = serialize($arr);
echo $serialize_var;
Copy after login

显示结果:

a:2:{s:5:"Peter";a:2:{s:7:"Country";s:3:"USA";s:3:"Age";i:20;}s:7:"Li Ming";a:2:{s:7:"Country";s:5:"CHINA";s:3:"Age";i:21;}}
Copy after login

这个结果看上去比JSON要复杂一些,其实也很简单,它说明的就是一些数据类型和结构。

以a:2:{s:7:"Country";s:3:"USA";s:3:"Age";i:20;}为例:

a:2说明这是个有两个元素的数组(array),s:7:"Country";s:3:"USA";为第一个元素,s:7说明这是有7个字符的字符串(string),后面i:20;也应该猜得到是整数(integer)20。

再来看一下这个例子:

程序5:

class test
{
    var $var = 0;
    function add(){
      echo $var+10;
    }
}
$unserialize_var = new test;
$serialize_var = serialize($unserialize_var);
echo $serialize_var;
$unserialize_var = null;
$unserialize_var = unserialize($serialize_var);
$unserialize_var->add();
Copy after login

显示结果:

O:4:"test":1:{s:3:"var";i:0;}
10
Copy after login

从这个例子中可以看出来,serialize对数据的类型和结构都进行的保存,unserialize后的变量仍然可以使用add()方法。

那么PHP和JSON有没有联系呢,熟悉PHP的朋友应该了解PHP5.2.0已经将JSON extension设置为默认组件,也就是说我们可以在PHP中进行JSON操作,其函数为json_encode和json_decode。

程序6:

$arr = array
       (
          'Name'=>'Peter',
          'Age'=>20
       );
$jsonencode = json_encode($arr);
echo $jsonencode;
Copy after login

显示结果:

{"Name":"Peter","Age":20}
Copy after login

这个结果和例一中test值是一样的,通过json_encode将PHP中的变量转换为JSON字符出表达式。

再来看看json_decode的用法。

程序7:

$var = '{"Name":"Peter","Age":20}';
$jsondecode = json_decode($var);
print_r($jsondecode);
Copy after login

显示结果:

stdClass Object ( [Name] => Peter [Age] => 20 )
Copy after login

这的确验证了,在JSON中{"Name":"Peter","Age":20}是一个对象,但是在PHP中也可以将其转为数组,在json_decode中将ASSOC参数设置为True即可。

程序8:

$var = '{"Name":"Peter","Age":20}';
$jsondecode = json_decode($var,true);
print_r($jsondecode);
Copy after login

显示结果:

Array ( [Name] => Peter [Age] => 20 )
Copy after login

另,需要注意的是JSON是基于Unicode格式,所以要进行中文操作要将其转化为UTF-8格式。

通过上面这些例子相信大家对于JSON和PHP的serialize、json_encode都有了初步了解,结合PHP、Javascript、JSON以及Ajax就可以完成强大的数据交互功能。

Statement of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Roblox: Bubble Gum Simulator Infinity - How To Get And Use Royal Keys
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Nordhold: Fusion System, Explained
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Mandragora: Whispers Of The Witch Tree - How To Unlock The Grappling Hook
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1670
14
PHP Tutorial
1274
29
C# Tutorial
1256
24
PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP: Handling Databases and Server-Side Logic PHP: Handling Databases and Server-Side Logic Apr 15, 2025 am 12:15 AM

PHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.

See all articles