zoukankan      html  css  js  c++  java
  • 封装json格式化函数

    <?php
    function indent ($json) {
      $result = '';
      $pos = 0;
      $strLen = strlen($json);
      $indentStr = ' ';
      $newLine = "
    ";
      $prevChar = '';
      $outOfQuotes = true;
    
      for ($i=0; $i<=$strLen; $i++) {
          // 抓取字符串中的下一个字符
          $char = substr($json, $i, 1);
          // Are we inside a quoted string?
          if ($char == '"' && $prevChar != '\') {
             $outOfQuotes = !$outOfQuotes;
             // 如果这个字符是元素的结尾,输出新行并缩进下一行
          } else if(($char == '}' || $char == ']') && $outOfQuotes) {
             $result .= $newLine;
             $pos --;
            for ($j=0; $j<$pos; $j++) {
              $result .= $indentStr;
            }
          }
          //将字符添加到结果字符串中
          $result .= $char;
          // 如果最后一个字符是元素的开头,输出新行并缩进下一行
          if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
            $result .= $newLine;
            if ($char == '{' || $char == '[') {
               $pos ++;
            }
            for ($j = 0; $j < $pos; $j++) {
              $result .= $indentStr;
            }
          }
          $prevChar = $char;
      }
      return $result;
    }
    
    $arr = array(  
        'status' => true,  
        'errMsg' => '',  
        'member' =>array(  
            array(  
                'name' => '李逍遥',  
                'gender' => '男'  
            ),  
            array(  
                'name' => '赵灵儿',  
                'gender' => '女'  
            )  
        )  
    ); 
    $str = json_encode($arr);
    $json = indent($str);
    echo $json;
  • 相关阅读:
    python内置模块collections介绍
    Python的set集合详解
    不同 Python 数据类型的搜寻
    Python 分支、循环、条件与枚举
    ssrf爆破mysql
    php反序列化
    thinkphp历史漏洞
    Thinkphp 缓存RCE
    绕WAF文章收集
    mssql手工盲注
  • 原文地址:https://www.cnblogs.com/lonmyblog/p/9530663.html
Copyright © 2011-2022 走看看