PHP 사용자 정의 함수 형식 json 데이터 예

墨辰丷
풀어 주다: 2023-03-28 22:50:01
원래의
1468명이 탐색했습니다.

这篇文章主要介绍了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
  }
}
**/
?>
로그인 후 복사

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

相关推荐:

php实现URL加密解密

PHP读取zip文件的方法

PHP版单点登陆实现方案

위 내용은 PHP 사용자 정의 함수 형식 json 데이터 예의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

관련 라벨:
원천:php.cn
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!