Method to convert php array to json format, php array json format_PHP tutorial

WBOY
Release: 2016-07-13 10:04:30
Original
985 people have browsed it

How to convert php array to json format, php array json format

The example in this article describes the method of converting php array to json format. Share it with everyone for your reference. The specific implementation method is as follows:

Copy code The code is as follows: 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;
}

I hope this article will be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/965352.htmlTechArticleHow to convert php array into json format, php array json format This article describes how to convert php array into json format method. Share it with everyone for your reference. The specific implementation method is as follows: Copy...
Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template