array2json.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. <?php
  2. function array2json($arr) {
  3. if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
  4. $parts = array();
  5. $is_list = false;
  6. //Find out if the given array is a numerical array
  7. $keys = array_keys($arr);
  8. $max_length = count($arr)-1;
  9. if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {//See if the first key is 0 and last key is length - 1
  10. $is_list = true;
  11. for($i=0; $i<count($keys); $i++) { //See if each key correspondes to its position
  12. if($i != $keys[$i]) { //A key fails at position check.
  13. $is_list = false; //It is an associative array.
  14. break;
  15. }
  16. }
  17. }
  18. foreach($arr as $key=>$value) {
  19. if(is_array($value)) { //Custom handling for arrays
  20. if($is_list) $parts[] = array2json($value); /* :RECURSION: */
  21. else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
  22. } else {
  23. $str = '';
  24. if(!$is_list) $str = '"' . $key . '":';
  25. //Custom handling for multiple data types
  26. if(is_numeric($value)) $str .= $value; //Numbers
  27. elseif($value === false) $str .= 'false'; //The booleans
  28. elseif($value === true) $str .= 'true';
  29. else $str .= '"' . addslashes($value) . '"'; //All other things
  30. // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  31. $parts[] = $str;
  32. }
  33. }
  34. $json = implode(',',$parts);
  35. if($is_list) return '[' . $json . ']';//Return numerical JSON
  36. return '{' . $json . '}';//Return associative JSON
  37. }
  38. ?>