代码
<?php
function jsonFormat($json){
// 缩进处理
$ret = '';
$pos = 0;
$length = strlen($json);
$indent = isset($indent)? $indent : ' ';
$newline = "\n";
$prevchar = '';
$outofquotes = true;
for($i=0; $i<=$length; $i++){
$char = substr($json, $i, 1);
if($char=='"' && $prevchar!='\\'){
$outofquotes = !$outofquotes;
}
else if(($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;
}
echo jsonFormat(json_encode($data));