PHP custom function format json data example

墨辰丷
Release: 2023-03-28 22:50:01
Original
1530 people have browsed it

这篇文章主要介绍了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(&#39;a&#39; => 1, &#39;b&#39; => "脚本之家", &#39;c&#39; => 3, &#39;d&#39; => 4, &#39;e&#39; => 5));
$json = json_encode($arr);
function _format_json($json, $html = false) {
    $tabcount = 0;
    $result = &#39;&#39;;
    $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 &#39;{&#39;:
            $tabcount++;
            $result .= $char . $newline . str_repeat($tab, $tabcount);
            break;
          case &#39;}&#39;:
            $tabcount--;
            $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
            break;
          case &#39;,&#39;:
            $result .= $char . $newline . str_repeat($tab, $tabcount);
            break;
          case &#39;"&#39;:
            $inquote = !$inquote;
            $result .= $char;
            break;
          case &#39;\\&#39;:
            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
  }
}
**/
?>
Copy after login

总结:以上就是本篇文的全部内容,希望能对大家的学习有所帮助。

相关推荐:

php实现URL加密解密

PHP读取zip文件的方法

PHP版单点登陆实现方案

The above is the detailed content of PHP custom function format json data example. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!