helper_json.php 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. /**
  3. * [Discuz!] (C)2001-2099 Comsenz Inc.
  4. * This is NOT a freeware, use is subject to license terms
  5. *
  6. * $Id: helper_json.php 32779 2013-03-08 02:57:37Z zhangguosheng $
  7. */
  8. if(!defined('IN_DISCUZ')) {
  9. exit('Access Denied');
  10. }
  11. class helper_json {
  12. public static function encode($data) {
  13. switch ($type = gettype($data)) {
  14. case 'NULL':
  15. return 'null';
  16. case 'boolean':
  17. return ($data ? 'true' : 'false');
  18. case 'integer':
  19. case 'double':
  20. case 'float':
  21. return $data;
  22. case 'string':
  23. return '"' . addcslashes($data, "\r\n\t\"") . '"';
  24. case 'object':
  25. $data = get_object_vars($data);
  26. case 'array':
  27. $count = 0;
  28. $indexed = array();
  29. $associative = array();
  30. foreach ($data as $key => $value) {
  31. if($count !== NULL && (gettype($key) !== 'integer' || $count++ !== $key)) {
  32. $count = NULL;
  33. }
  34. $one = self::encode($value);
  35. $indexed[] = $one;
  36. $associative[] = self::encode($key) . ':' . $one;
  37. }
  38. if ($count !== NULL) {
  39. return '[' . implode(',', $indexed) . ']';
  40. } else {
  41. return '{' . implode(',', $associative) . '}';
  42. }
  43. default:
  44. return ''; // Not supported
  45. }
  46. }
  47. }
  48. ?>