这里有新鲜出炉的 PHP 设计模式,程序狗速度看过来!
PHP(外文名: Hypertext Preprocessor,中文名:"超文本预处理器")是一种通用开源脚本语言。语法吸收了 C 语言、Java 和 Perl 的特点,入门门槛较低,易于学习,使用广泛,主要适用于 web 开发领域。PHP 的文件后缀名为 php。
这篇文章主要介绍了 PHP 自定义函数格式化 json 数据的方法, 结合实例形式分析了 php 通过自定义函数进行字符串与数组的遍历、转换、计算等操作实现 json 数据格式化的功能, 需要的朋友可以参考下
本文实例讲述了 PHP 自定义函数格式化 json 数据的方法。分享给大家供大家参考,具体如下:
- <?php
- /**
- * Formats a JSON string for pretty printing
- *
- * @param string $json The JSON to 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' => "PHPERZ", '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
- }
- }
- **/
- ?>
希望本文所述对大家 PHP 程序设计有所帮助。
来源: http://www.phperz.com/article/17/0802/342717.html