Share a json data formatting function for PHP. Today, I saw a piece of code on the mango site, which was quite good, so I reprinted it. The following is the original text. Format JSON data in string form into indent form. I usually see a piece of code in the mango site using json today. it feels pretty good, so I reprinted it. The following is the original text.
Format JSON data in string form into indent form. Generally, the JSON string converted using json_encode is not indented. this method is much better.
Here, tab indentation is used by default. to change it to a space, replace the variable $ indentStr.
/**
* Indents a flat JSON string to make it more human-readable.
* @ Param string $ json The original JSON string to process.
* @ Return string Indented version of the original JSON string.
*/
Function indent ($ json ){
$ Result = '';
$ Pos = 0;
$ StrLen = strlen ($ json );
$ IndentStr = '';
$ NewLine = "\ n ";
$ PrevChar = '';
$ OutOfQuotes = true;
For ($ I = 0; $ I <= $ strLen; $ I ++ ){
// Grab the next character in the string.
$ Char = substr ($ json, $ I, 1 );
// Are we inside a quoted string?
If ($ char = '"' & $ prevChar! = '\\'){
$ OutOfQuotes =! $ OutOfQuotes;
// If this character is the end of an element,
// Output a new line and indent the next line.
} Else if ($ char = '}' | $ char = ']') & $ outOfQuotes ){
$ Result. = $ newLine;
$ Pos --;
For ($ j = 0; $ j <$ pos; $ j ++ ){
$ Result. = $ indentStr;
}
}
// Add the character to the result string.
$ Result. = $ char;
// If the last character was the beginning of an element,
// Output a new line and indent the next line.
If ($ char = ',' | $ char = '{' | $ char = '[') & $ outOfQuotes ){
$ Result. = $ newLine;
If ($ char = '{' | $ char = '['){
$ Pos ++;
}
For ($ j = 0; $ j <$ pos; $ j ++ ){
$ Result. = $ indentStr;
}
}
$ PrevChar = $ char;
}
Return $ result;
}
Bytes. The following is the original text. Format JSON data in string form into indent form. Json...