PHP自定义函数格式化json数据示例
作者:懒人 时间:2023-07-17 07:17:45
本文实例讲述了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' => "asp之家", '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程序设计有所帮助。
标签:PHP,格式化,json
0
投稿
猜你喜欢
Python模拟鼠标点击实现方法(将通过实例自动化模拟在360浏览器中自动搜索python)
2021-06-11 17:17:54
Python轻松破解加密压缩包教程详解
2021-04-12 13:26:45
Mysql limit 优化,百万至千万级快速分页 复合索引的引用并应用于轻量级框架
2024-01-14 00:42:39
asp如何限制重复订阅邮件或重复投票?
2010-06-09 18:48:00
Python的命令行参数实例详解
2023-06-11 09:05:45
python中numpy 常用操作总结
2021-01-10 05:01:57
十行Python代码实现文字识别功能
2024-01-01 14:55:09
使用Python对接OpenAi API实现智能QQ机器人的方法
2023-08-12 10:24:25
python模块的安装以及安装失败的解决方法
2023-09-14 06:33:04
mysql中的mvcc 原理详解
2024-01-18 05:10:13
聚焦 DreamWeaver MX 2004
2010-03-25 12:22:00
使用Python和百度语音识别生成视频字幕的实现
2022-02-28 23:12:42
python神经网络Keras构建CNN网络训练
2022-08-16 08:42:37
python批量下载抖音视频
2023-09-05 11:26:14
JavaScript画圆
2010-01-22 15:57:00
Django的restframework接口框架自定义返回数据格式的示例详解
2023-06-13 05:13:51
XML入门精解之文件格式定义
2008-02-25 13:57:00
在Python函数中输入任意数量参数的实例
2022-07-09 04:58:08
Python 爬虫批量爬取网页图片保存到本地的实现代码
2021-06-23 02:12:34
ASP IE地址栏参数的判断
2011-04-03 11:21:00