12345678910111213141516171819202122232425262728293031323334353637383940414243 |
- <?php
- function array2json($arr) {
- if(function_exists('json_encode')) return json_encode($arr);
- $parts = array();
- $is_list = false;
-
- $keys = array_keys($arr);
- $max_length = count($arr)-1;
- if(($keys[0] == 0) and ($keys[$max_length] == $max_length)) {
- $is_list = true;
- for($i=0; $i<count($keys); $i++) {
- if($i != $keys[$i]) {
- $is_list = false;
- break;
- }
- }
- }
- foreach($arr as $key=>$value) {
- if(is_array($value)) {
- if($is_list) $parts[] = array2json($value);
- else $parts[] = '"' . $key . '":' . array2json($value);
- } else {
- $str = '';
- if(!$is_list) $str = '"' . $key . '":';
-
- if(is_numeric($value)) $str .= $value;
- elseif($value === false) $str .= 'false';
- elseif($value === true) $str .= 'true';
- else $str .= '"' . addslashes($value) . '"';
-
- $parts[] = $str;
- }
- }
- $json = implode(',',$parts);
-
- if($is_list) return '[' . $json . ']';
- return '{' . $json . '}';
- }
- ?>
|