BMLT Root Server
Functions
Array2Json.php File Reference

Go to the source code of this file.

Functions

 array2json ($arr)
 Encodes a given associative array into a JSON object string. More...
 

Function Documentation

array2json (   $arr)

Encodes a given associative array into a JSON object string.

Returns
a JSON object, as a string.
Parameters
$arrAn associative string, to be encoded as JSON.

Definition at line 41 of file Array2Json.php.

Referenced by c_comdef_admin_ajax_handler\HandleAccountChange(), parse_redirect(), c_comdef_admin_ajax_handler\TranslateToJSON(), TranslateToJSON(), and whitespace_warnings().

43  {
44  $parts = array();
45  // See if we are an associative array.
46  $is_list = (count(array_filter(array_keys($arr), 'is_numeric')) == count($arr)) && (array_keys($arr) === range(0, count($arr) - 1));
47 
48  foreach ($arr as $key => $value) {
49  if (is_array($value) && count($value)) { //Custom handling for arrays
50  if ($is_list) {
51  $parts[] = array2json($value); /* :RECURSION: */
52  } else {
53  $parts[] = '"' . $key . '":' . array2json($value); /* :RECURSION: */
54  }
55  } else {
56  $str = '';
57  if ($key === 'json_data') { // JSON data is passed through without any vetting or modification (so it can easily bork the stream).
58  $str = '"'.$key.'":'.$value;
59  } else {
60  if (!$is_list) {
61  $str = '"' . $key . '":';
62  }
63 
64  //Custom handling for multiple data types
65  if (isset($value)) {
66  if (is_integer($value)) {
67  $str .= $value;
68  } elseif (is_bool($value)) {
69  $str .= $value ? 'true': 'false';
70  } else {
71  $str .= '"' . trim(json_encode(str_replace('"', '"', $value), JSON_UNESCAPED_SLASHES), '"') . '"'; //All other things
72  }
73  } else {
74  $str .= '""'; //All other things
75  }
76  }
77 
78  // :TODO: Is there any more datatype we should be in the lookout for? (Object?)
79 
80  $parts[] = $str;
81  }
82  }
83 
84  $json = implode(',', $parts);
85 
86  if ($is_list) {
87  return '[' . $json . ']'; //Return numerical JSON
88  } else {
89  return '{' . $json . '}'; //Return associative JSON
90  }
91 }
array2json($arr)
Encodes a given associative array into a JSON object string.
Definition: Array2Json.php:41