PHP自定义函数格式化json数据实例

墨辰丷
墨辰丷 原创
2023-03-28 22:50:01 1055浏览

这篇文章主要介绍了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' => "脚本之家", '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实现URL加密解密

PHP读取zip文件的方法

PHP版单点登陆实现方案

以上就是PHP自定义函数格式化json数据实例的详细内容,更多请关注php中文网其它相关文章!

声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。