This article mainly introduces the PHP custom function format JSON data method, combined with the instance form analysis PHP through the custom function to the string and array of the traversal, conversion, computation and other operations to implement the JSON data format function, the need for friends can refer to the following
Specific as follows:
<?php/** * Formats A JSON string for pretty printing * * @param string $json The JSON-make pretty * @param BOOL $html Insert nonbreaking spaces and <br/>s for tabs and linebreaks * @return string the prettified output */$arr = array ("ret" =>0, "Data" =>array (' a ' = = 1, ' b ' = "Home of script", ' c ' = = 3, ' d ' = 4, ' e ' = 5) "); $json = Json_encode ($arr); function _format_json ($json, $html = False) {$tabcount = 0; $result = "; $inquote = false; $ignorenext = false; if ($html) {$tab = ""; $newline = "<br/>"; } else {$tab = "\ t"; $newline = "\ n"; } for ($i = 0; $i < strlen ($json); $i + +) {$char = $json [$i]; if ($ignorenext) {$result. = $char; $ignorenext = false; } else {switch ($char) {case ' {': $tabcount + +; $result. = $char. $newline. Str_repeat ($tab, $tabcount); Break Case '} ': $tabcount-; $result = Trim ($result). $newline. Str_repeat ($tab, $tabcount). $char; Break Case ', ': $result. = $char. $newline. Str_repeat ($tab, $tabcount); Break Case ' "': $inquote =! $inquote; $result. = $char; Break Case ' \ \ ': if ($inquote) $ignorenext = true; $result. = $char; Break Default: $result. = $char; }}} return $result; }echo _format_json ($json);/*{"ret": 0, "data": {"a": 1, "B": "\u811a\u672c\u4e4b\u5bb6", "C": 3, "D": 4, "E": 5}}**/?>
Summary: The above is the entire content of this article, I hope to be able to help you learn.