PHP serialize & JSON 解析
对于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说起,看一个简单的实例。
例一:
var test = { " Name " : " Peter " , " Age " : 20 };
document.write(test.Name + " : " + test.Age);
显示结果:
Peter: 20
变量test中{"Name":"Peter","Age":20}为一个有2个元素的对象(感觉就像PHP的数组):
Name为Peter,Age为20。
当然也可以变得复杂些。
例二:
var test = { " User " :{ " Name " : " Peter " , " Age " : 20 }, " Company " : " FORD " };
document.write(test.User.Name + " : " + test.Company);
显示结果:
Peter: FORD
这个例子中User元素中包含了Name和Age。
如果要体现多个User,则需要使用数组,区别于对象的"{}",数组使用"[]"。
例三:
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"]);
显示结果:
Li Ming: Benz
通过以上简单实例就能将一些复杂数据通过一个字符串来进行传递,再配合上Ajax的确是方便很多。
下面再来看看PHP的serialize函数的作用。
例四:
$arr = array
(
' Peter ' => array
(
' Country ' => ' USA ' ,
' Age ' => 20
) ,
' Li Ming ' => array
(
' Country ' => ' CHINA ' ,
' Age ' => 21
)
);
$serialize_var = serialize ( $arr );
echo $serialize_var ;
显示结果:
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 ;}}
这个结果看上去比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。
再来看一下这个例子,
例五:
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();
显示结果:
O : 4 : " test " : 1 : {s : 3 : " var " ;i : 0 ;}
10
从这个例子中可以看出来,serialize对数据的类型和结构都进行的保存,
unserialize后的变量仍然可以使用add()方法。
那么PHP和JSON有没有联系呢,熟悉PHP的朋友应该了解PHP5.2.0已经将JSON extension设置为默认组件,也就是说我们可以在PHP中进行JSON操作,其函数为json_encode和json_decode。
例六:
$arr = array
(
' Name ' => ' Peter ' ,
' Age ' => 20
);
$jsonencode = json_encode( $arr );
echo $jsonencode ;
显示结果:
{ " Name " : " Peter " , " Age " : 20 }
这个结果和例一中test值是一样的,通过json_encode将PHP中的变量转换为JSON字符出表达式。
再来看看json_decode的用法。
例七:
$var = ' {"Name":"Peter","Age":20} ' ;
$jsondecode = json_decode( $var );
print_r ( $jsondecode );
显示结果:
stdClass Object ( [Name] => Peter [Age] => 20 )
这的确验证了,在JSON中{"Name":"Peter","Age":20}是一个对象,但是在PHP中也可以将其转为数组,在json_decode中将ASSOC参数设置为True即可。
例八:
$var = ' {"Name":"Peter","Age":20} ' ;
$jsondecode = json_decode( $var , true );
print_r ( $jsondecode );
显示结果:
Array ( [Name] => Peter [Age] => 20 )
另,需要注意的是JSON是基于Unicode格式,所以要进行中文操作要将其转化为UTF-8格式。
通过上面这些例子相信大家对于JSON和PHP的serialize、json_encode都有了初步了解,
结合PHP、Javascript、JSON以及Ajax就可以完成强大的数据交互功能。
相关参考资料:
PHP JSON Functions: http://cn.php.net/manual/en/ref.json.php
JSON Introduction:http://www.json.org/json-zh.html
网友实例: http://www.only4.cn/archives/95
http://www.openphp.cn/blog.php?blog_id=12

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Long URLs, often cluttered with keywords and tracking parameters, can deter visitors. A URL shortening script offers a solution, creating concise links ideal for social media and other platforms. These scripts are valuable for individual websites a

Following its high-profile acquisition by Facebook in 2012, Instagram adopted two sets of APIs for third-party use. These are the Instagram Graph API and the Instagram Basic Display API.As a developer building an app that requires information from a

Laravel simplifies handling temporary session data using its intuitive flash methods. This is perfect for displaying brief messages, alerts, or notifications within your application. Data persists only for the subsequent request by default: $request-

This is the second and final part of the series on building a React application with a Laravel back-end. In the first part of the series, we created a RESTful API using Laravel for a basic product-listing application. In this tutorial, we will be dev

Laravel provides concise HTTP response simulation syntax, simplifying HTTP interaction testing. This approach significantly reduces code redundancy while making your test simulation more intuitive. The basic implementation provides a variety of response type shortcuts: use Illuminate\Support\Facades\Http; Http::fake([ 'google.com' => 'Hello World', 'github.com' => ['foo' => 'bar'], 'forge.laravel.com' =>

The PHP Client URL (cURL) extension is a powerful tool for developers, enabling seamless interaction with remote servers and REST APIs. By leveraging libcurl, a well-respected multi-protocol file transfer library, PHP cURL facilitates efficient execution of various network protocols, including HTTP, HTTPS, and FTP. This extension offers granular control over HTTP requests, supports multiple concurrent operations, and provides built-in security features.

Do you want to provide real-time, instant solutions to your customers' most pressing problems? Live chat lets you have real-time conversations with customers and resolve their problems instantly. It allows you to provide faster service to your custom

The 2025 PHP Landscape Survey investigates current PHP development trends. It explores framework usage, deployment methods, and challenges, aiming to provide insights for developers and businesses. The survey anticipates growth in modern PHP versio
