Advertisement
arijulianto

array2json

Nov 20th, 2019
212
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.69 KB | None | 0 0
  1. function array2json($arr) {
  2.     if(function_exists('json_encode')) return json_encode($arr); //Lastest versions of PHP already has this functionality.
  3.     $parts = array();
  4.     $is_list = false;
  5.  
  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.  
  19.     foreach($arr as $key=>$value) {
  20.         if(is_array($value)) { //Custom handling for arrays
  21.             if($is_list) $parts[] = array2json($value); /* :RECURSION: */
  22.             else $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
  23.         } else {
  24.             $str = '';
  25.             if(!$is_list) $str = '"' . $key . '":';
  26.  
  27.             //Custom handling for multiple data types
  28.             if(is_numeric($value)) $str .= $value; //Numbers
  29.             elseif($value === false) $str .= 'false'; //The booleans
  30.             elseif($value === true) $str .= 'true';
  31.             else $str .= '"' . addslashes($value) . '"'; //All other things
  32.             // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
  33.  
  34.             $parts[] = $str;
  35.         }
  36.     }
  37.     $json = implode(',',$parts);
  38.    
  39.     if($is_list) return '[' . $json . ']';//Return numerical JSON
  40.     return '{' . $json . '}';//Return associative JSON
  41. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement