封装json格式化函数
<?php function indent ($json) { $result = ''; $pos = 0; $strLen = strlen($json); $indentStr = ' '; $newLine = "\n"; $prevChar = ''; $outOfQuotes = true; for ($i=0; $i<=$strLen; $i++) { // 抓取字符串中的下一个字符 $char = substr($json, $i, 1); // Are we inside a quoted string? if ($char == '"' && $prevChar != '\\') { $outOfQuotes = !$outOfQuotes; // 如果这个字符是元素的结尾,输出新行并缩进下一行 } else if(($char == '}' || $char == ']') && $outOfQuotes) { $result .= $newLine; $pos --; for ($j=0; $j<$pos; $j++) { $result .= $indentStr; } } //将字符添加到结果字符串中 $result .= $char; // 如果最后一个字符是元素的开头,输出新行并缩进下一行 if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) { $result .= $newLine; if ($char == '{' || $char == '[') { $pos ++; } for ($j = 0; $j < $pos; $j++) { $result .= $indentStr; } } $prevChar = $char; } return $result; } $arr = array( 'status' => true, 'errMsg' => '', 'member' =>array( array( 'name' => '李逍遥', 'gender' => '男' ), array( 'name' => '赵灵儿', 'gender' => '女' ) ) ); $str = json_encode($arr); $json = indent($str); echo $json;