4 * Converts an associative array of arbitrary depth and dimension into JSON representation. Used for compatibility with older PHP builds.
\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
11 function yourls_array_to_json( $array ){
\r
13 if( !is_array( $array ) ){
\r
17 $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
\r
20 $construct = array();
\r
21 foreach( $array as $key => $value ){
\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
27 if( is_numeric($key) ){
\r
30 $key = "'".addslashes($key)."'";
\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
39 // Add to staging array:
\r
40 $construct[] = "$key: $value";
\r
43 // Then we collapse the staging array into the JSON form:
\r
44 $result = "{ " . implode( ", ", $construct ) . " }";
\r
46 } else { // If the array is a vector (not associative):
\r
48 $construct = array();
\r
49 foreach( $array as $value ){
\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
58 // Add to staging array:
\r
59 $construct[] = $value;
\r
62 // Then we collapse the staging array into the JSON form:
\r
63 $result = "[ " . implode( ", ", $construct ) . " ]";
\r