PHP生成JSON-json_encode

Author Avatar
在路上 12月 13, 2011

生成JSON: PHP(PHP 5 >= 5.2.0, PECL json >= 1.2.0):

1
string json_encode ( mixed $value [, int $options = 0 ] )

如:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
$array = array('sun', 'chun', 'man');
echo json_encode($array).PHP_EOL;
$array = array(0 => 'sun', 1 => 'chun', 2 => 'man');
echo json_encode($array).PHP_EOL;
$array = array('0' => 'sun', '1' => 'chun', '2' => 'man');
echo json_encode($array).PHP_EOL;
$array = array(4 => 'sun', 5 => 'chun', 9 => 'man');
echo json_encode($array).PHP_EOL;
$array = array(5 => 'sun', 4 => 'chun', 9 => 'man');
echo json_encode($array).PHP_EOL;
$array = array('4' => 'sun', '5' => 'chun', '9' => 'man');
echo json_encode($array).PHP_EOL;
$array = array('a0' => 'sun', 'a1' => 'chun', 'a2' => 'man');
echo json_encode($array).PHP_EOL;
$array = array('1' => 'sun', '2' => 'chun', '3' => 'man');
echo json_encode($array).PHP_EOL;
$array = array(1 => 'sun', 2 => 'chun', 3 => 'man');
echo json_encode($array).PHP_EOL;
$array = array(0 => 'sun', 2 => 'chun', 3 => 'man');
echo json_encode($array).PHP_EOL;
$array = array(0 => 'sun', 'chun', 'man');
echo json_encode($array).PHP_EOL;

输出:

1
2
3
4
5
6
7
8
9
10
11
["sun","chun","man"]
["sun","chun","man"]
["sun","chun","man"]
{"4":"sun","5":"chun","9":"man"}
{"5":"sun","4":"chun","9":"man"}
{"4":"sun","5":"chun","9":"man"}
{"a0":"sun","a1":"chun","a2":"man"}
{"1":"sun","2":"chun","3":"man"}
{"1":"sun","2":"chun","3":"man"}
{"0":"sun","2":"chun","3":"man"}
["sun","chun","man"]

从上面结果可以看出: 只要数组的索引为0,1,2,...或'0', '1', '2', ...,即数组索引以0或'0'开头,其他索引为自然顺序,且索引相差为1,则JSON输出为数组[], 否则为对象{}.

PHP 的json_encode函数第二个参数决定数组中哪类字符串需要编码,如

1
2
3
4
5
6
7
8
9
JSON_HEX_QUOT, 双引号
JSON_HEX_TAG, XML标签
JSON_HEX_AMP, 实体
JSON_HEX_APOS, 单引号
JSON_NUMERIC_CHECK,
JSON_PRETTY_PRINT,
JSON_UNESCAPED_SLASHES,
JSON_FORCE_OBJECT,
JSON_UNESCAPED_UNICODE, unicode字符

参考: http://cn2.php.net/json_encode

2017-08-26 整理