Home >Backend Development >PHP Tutorial >How to convert php array to json format_PHP tutorial

How to convert php array to json format_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:04:24851browse

How to convert php array to json format

This article mainly introduces the method of converting php array to json format, and analyzes the method of php operating array and json format data with examples. , friends in need can refer to it

The example in this article describes how to convert a php array into json format. Share it with everyone for your reference. The specific implementation method is as follows:

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/965530.htmlTechArticleHow to convert php array to json format This article mainly introduces the method of converting php array to json format, examples Analyzed the methods of operating arrays and json format data in PHP. Friends in need can refer to...
Statement:
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