php格式化json函数示例代码

这篇文章主要介绍了php格式化json函数,结合实例形式分析了php使用自定义函数实现json格式化的方法,涉及php数组转json、流程控制及字符串操作等技巧,需要的朋友可以参考下。

本文讲述了php格式化json函数的示例代码,分享给大家供大家参考,具体如下:

  1. <?php
  2. $arr = array("ret"=>0,"data"=>array('a' => 1, 'b' => '2', 'c' => 3, 'd' => 4, 'e' => 5));
  3. $json = json_encode($arr);
  4. /**
  5. * Formats a JSON string for pretty printing
  6. *
  7. * @param string $json The JSON to make pretty
  8. * @param bool $html Insert nonbreaking spaces and <br />s for tabs and linebreaks
  9. * @return string The prettified output
  10. */
  11. function _format_json($json, $html = false) {
  12. $tabcount = 0;
  13. $result = '';
  14. $inquote = false;
  15. $ignorenext = false;
  16. if ($html) {
  17. $tab = "&nbsp;&nbsp;&nbsp;";
  18. $newline = "<br/>";
  19. } else {
  20. $tab = "\t";
  21. $newline = "\n";
  22. }
  23. for($i = 0; $i < strlen($json); $i++) {
  24. $char = $json[$i];
  25. if ($ignorenext) {
  26. $result .= $char;
  27. $ignorenext = false;
  28. } else {
  29. switch($char) {
  30. case '{':
  31. $tabcount++;
  32. $result .= $char . $newline . str_repeat($tab, $tabcount);
  33. break;
  34. case '}':
  35. $tabcount--;
  36. $result = trim($result) . $newline . str_repeat($tab, $tabcount) . $char;
  37. break;
  38. case ',':
  39. $result .= $char . $newline . str_repeat($tab, $tabcount);
  40. break;
  41. case '"':
  42. $inquote = !$inquote;
  43. $result .= $char;
  44. break;
  45. case '\\':
  46. if ($inquote) $ignorenext = true;
  47. $result .= $char;
  48. break;
  49. default:
  50. $result .= $char;
  51. }
  52. }
  53. }
  54. return $result;
  55. }
  56. echo _format_json($json);
  57. /*
  58. {
  59. "ret": 0,
  60. "data": {
  61. "a": 1,
  62. "b": 2,
  63. "c": 3,
  64. "d": 4,
  65. "e": 5
  66. }
  67. }
  68. **/
  69. ?>