当前位置:Gxlcms > PHP教程 > PHP自定义函数格式化json数据实例

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

时间:2021-07-01 10:21:17 帮助过:21人阅读

这篇文章主要介绍了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数据实例的详细内容,更多请关注Gxl网其它相关文章!

人气教程排行