作用:对变量进行 JSON 编码
语法: string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )
value :除了resource 类型之外,可以为任何数据类型。所有字符串数据的编码必须是 UTF-8。
options:由以下常量组成的二进制掩码
:JSON_HEX_QUOT,JSON_HEX_TAG,JSON_HEX_AMP,JSON_HEX_APOS,JSON_NUMERIC_CHECK,JSON_PRETTY_PRINT,JSON_FORCE_OBJECT,JSON_PRESERVE_ZERO_FRACTION,JSON_UNESCAPED_UNICODE(避免中文这些转码等,对应数字256),JSON_UNESCAPED_SLASHES(不转义反斜杠,对应的数字64),JSON_PARTIAL_OUTPUT_ON_ERROR。 关于 JSON 常量详情参考JSON 常量页面,也可以参考http://blog.csdn.net/any2mobile/article/details/8717180。
depth:设置最大深度。 必须大于0。
返回值说明:成功则返回 JSON 编码的 string 或者在失败时返回 FALSE 。
如果value是一个数组,如果是无下标的数组(即默认下标0,1,2,3),则返回值是[]包起来的数组,否则,是{}包起来的对象
<?php
$arr = array(1,2,3,4);
$arr2 = array('a','b','c','d');
$arr3 = array(0=>1,1=>2,2=>3,3=>4);
$arr4 = array(1=>1,2=>2,3=>3,4=>4);
$arr5 = array('0'=>1,'1'=>2,'2'=>3,'3'=>4);
$arr6 = array('a'=>'a','b'=>'b','c'=>'c','d'=>'d');
$arr7 = array(
array(1,2,3,4),
array('a','b','c','d'),
array('a'=>'a','b'=>'b','c'=>'c','d'=>'d')
);
$arr8 = array(
'one' => array(1,2,3,4),
'two'=> array('a','b','c','d'),
'three' => array('a'=>'a','b'=>'b','c'=>'c','d'=>'d')
);
var_dump(json_encode($arr));
//结果: [1,2,3,4]
var_dump(json_encode($arr2));
//结果: ["a","b","c","d"]
var_dump(json_encode($arr3));
//结果: [1,2,3,4]
var_dump(json_encode($arr4));
//结果: {"1":1,"2":2,"3":3,"4":4}
var_dump(json_encode($arr5));
//结果: [1,2,3,4]
var_dump(json_encode($arr6));
//结果: {"a":"a","b":"b","c":"c","d":"d"}
var_dump(json_encode($arr7));
//结果: [[1,2,3,4],["a","b","c","d"],{"a":"a","b":"b","c":"c","d":"d"}]
var_dump(json_encode($arr8));
//结果: {"one":[1,2,3,4],"two":["a","b","c","d"],"three":{"a":"a","b":"b","c":"c","d":"d"}}
|