PHP json_encode

查看新版的PHP手册中JSON函数一节,JSON就增加了两个API,json_decode(),对一个json字符串进行解码,json_encode()是生成一个json字符串,我们就简单的测试一下。

构建如下PHP代码:

<? php

 

//对象 

class JsonTest{

var $id = 1;

var $name = 'heiyeluren';

var $gender = '';

}

$obj = new JsonTest;

echo json_encode($obj)."<br /> ";

 

//数字索引数组 

$arr1 = array(1, 'heiyeluren', '');

echo json_encode($arr1)."<br /> ";

 

//关联索引数组 

$arr2 = array("id"=>1, "name"=>'heiyeluren', "gender"=>'');

echo json_encode($arr2)."<br /> ";

 

//多维数字索引数组 

$arr3 = array(array(1, 'heiyeluren', ''), array(1, 'heiyeluren', ''));

echo json_encode($arr3)."<br /> ";

 

//关联索引数组 

$arr4 = array(array("id"=>1, "name"=>'heiyeluren', "gender"=>''), array("id"=>1, "name"=>'heiyeluren', "gender"=>''));

echo json_encode($arr4)."<br /> ";

?> 

 

浏览器输出:

{"id":1,"name":"heiyeluren","gender":""}

 

[1,"heiyeluren",""]

{"id":1,"name":"heiyeluren","gender":""}

[[1,"heiyeluren","\u7537"],[1,"heiyeluren","\u7537"]]

[{"id":1,"name":"heiyeluren","gender":"\u7537"},{"id":1,"name":"heiyeluren","gender":"\u7537"}]

 

按照JSON格式定义,我们可以发现上面的几个特点:

1. 纯的数字索引是按照JavaScript能够识别的数组来存储的

2. 关联索引数组是按照JavaScript对象的形式来构造的

3. 多维关联索引是按照外围是JavaScript数组,中间的索引数组是对象

4. 不显示中文,中文将全部被编码.


你可能感兴趣的:(JavaScript,json,PHP,浏览器,api,Class)