]> CyberLeo.Net >> Repos - Github/YOURLS.git/blob - includes/functions-json.php
Initial commit (importing from http://svn.planetozh.com/ozhin)
[Github/YOURLS.git] / includes / functions-json.php
1 <?php\r
2 \r
3 /**\r
4  * Converts an associative array of arbitrary depth and dimension into JSON representation. Used for compatibility with older PHP builds.\r
5  *\r
6  * @param $array The array to convert.\r
7  * @return mixed The resulting JSON string, or false if the argument was not an array.\r
8  * @author Andy Rusterholz\r
9  * @link http://php.net/json_encode (see comments)\r
10  */\r
11 function yourls_array_to_json( $array ){\r
12 \r
13     if( !is_array( $array ) ){\r
14         return false;\r
15     }\r
16 \r
17     $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));\r
18     if( $associative ){\r
19 \r
20         $construct = array();\r
21         foreach( $array as $key => $value ){\r
22 \r
23             // We first copy each key/value pair into a staging array,\r
24             // formatting each key and value properly as we go.\r
25 \r
26             // Format the key:\r
27             if( is_numeric($key) ){\r
28                 $key = "key_$key";\r
29             }\r
30             $key = "'".addslashes($key)."'";\r
31 \r
32             // Format the value:\r
33             if( is_array( $value )){\r
34                 $value = array_to_json( $value );\r
35             } else if( !is_numeric( $value ) || is_string( $value ) ){\r
36                 $value = "'".addslashes($value)."'";\r
37             }\r
38 \r
39             // Add to staging array:\r
40             $construct[] = "$key: $value";\r
41         }\r
42 \r
43         // Then we collapse the staging array into the JSON form:\r
44         $result = "{ " . implode( ", ", $construct ) . " }";\r
45 \r
46     } else { // If the array is a vector (not associative):\r
47 \r
48         $construct = array();\r
49         foreach( $array as $value ){\r
50 \r
51             // Format the value:\r
52             if( is_array( $value )){\r
53                 $value = array_to_json( $value );\r
54             } else if( !is_numeric( $value ) || is_string( $value ) ){\r
55                 $value = "'".addslashes($value)."'";\r
56             }\r
57 \r
58             // Add to staging array:\r
59             $construct[] = $value;\r
60         }\r
61 \r
62         // Then we collapse the staging array into the JSON form:\r
63         $result = "[ " . implode( ", ", $construct ) . " ]";\r
64     }\r
65 \r
66     return $result;\r
67 }\r
68 \r
69 ?>