-
Notifications
You must be signed in to change notification settings - Fork 9
/
jsonFormat.php
72 lines (55 loc) · 1.55 KB
/
jsonFormat.php
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
<?php
/** Json数据格式化
* @param Mixed $data 数据
* @param String $indent 缩进字符,默认4个空格
* @return JSON
*/
function jsonFormat($data, $indent=null){
// 对数组中每个元素递归进行urlencode操作,保护中文字符
array_walk_recursive($data, 'jsonFormatProtect');
// json encode
$data = json_encode($data);
// 将urlencode的内容进行urldecode
$data = urldecode($data);
// 缩进处理
$ret = '';
$pos = 0;
$length = strlen($data);
$indent = isset($indent)? $indent : ' ';
$newline = "\n";
$prevchar = '';
$outofquotes = true;
for($i=0; $i<=$length; $i++){
$char = substr($data, $i, 1);
if($char=='"' && $prevchar!='\\'){
$outofquotes = !$outofquotes;
}elseif(($char=='}' || $char==']') && $outofquotes){
$ret .= $newline;
$pos --;
for($j=0; $j<$pos; $j++){
$ret .= $indent;
}
}
$ret .= $char;
if(($char==',' || $char=='{' || $char=='[') && $outofquotes){
$ret .= $newline;
if($char=='{' || $char=='['){
$pos ++;
}
for($j=0; $j<$pos; $j++){
$ret .= $indent;
}
}
$prevchar = $char;
}
return $ret;
}
/** 将数组元素进行urlencode
* @param String $val
*/
function jsonFormatProtect(&$val){
if($val!==true && $val!==false && $val!==null){
$val = urlencode($val);
}
}
?>