myhduck's Octopress Blog

I want fly well

Array to Json

| Comments

array to json

요즘 업무상 PHP를 자주 사용하는데
php5.2이상에서는 json_encode()를 사용하면 쉽게 array를 json형태로 변환할 수 있다
하지만 php5.2하위 버젼에서는 지원하지 않기 때문에 만들어 써야한다

array_to_json
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
<?php
function array_to_json( $array ){

      if( !is_array( $array ) ){
          return false;
      }

      $associative = count( array_diff( array_keys($array), array_keys( array_keys( $array )) ));
      if( $associative ){

          $construct = array();
          foreach( $array as $key => $value ){

              // We first copy each key/value pair into a staging array,
              // formatting each key and value properly as we go.

              // Format the key:
              if( is_numeric($key) ){
                  $key = "key_$key";
              }
              $key = "\"".addslashes($key)."\"";

              // Format the value:
              if( is_array( $value )){
                  $value = array_to_json( $value );
              } else if( !is_numeric( $value ) || is_string( $value ) ){
                  $value = "\"".addslashes($value)."\"";
              }

              // Add to staging array:
              $construct[] = "$key: $value";
          }

          // Then we collapse the staging array into the JSON form:
          $result = "{ " . implode( ", ", $construct ) . " }";

      } else { // If the array is a vector (not associative):

          $construct = array();
          foreach( $array as $value ){

              // Format the value:
              if( is_array( $value )){
                  $value = array_to_json( $value );
              } else if( !is_numeric( $value ) || is_string( $value ) ){
                  $value = "'".addslashes($value)."'";
              }

              // Add to staging array:
              $construct[] = $value;
          }

          // Then we collapse the staging array into the JSON form:
          $result = "[ " . implode( ", ", $construct ) . " ]";
      }

      return $result;
  }
?> 

이걸로 만사 ok!!

Comments