php数组转成json格式的方法

yipeiwu_com6年前PHP代码库

本文实例讲述了php数组转成json格式的方法。分享给大家供大家参考。具体实现方法如下:

复制代码 代码如下:
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;
}

希望本文所述对大家的php程序设计有所帮助。

相关文章

php中stdClass的用法分析

本文实例分析了php中stdClass的用法。分享给大家供大家参考。具体分析如下: stdclass在php中是预定义的几个类之一,是zent保留的一个类。实际上它是PHP提供的一个基类...

浅析php插件 HTMLPurifier HTML解析器

浅析php插件 HTMLPurifier HTML解析器

HTMLPurifier插件的使用下载HTMLPurifier插件HTMLPurifier插件有用的部分是 library 使用HTMLPurifier library类库第一种方式复制...

curl 出现错误的调试方法(必看)

实例如下: private function httpGet($url) { $curl = curl_init(); curl_setopt($curl,...

php echo()和print()、require()和include()函数区别说明

1.echo和print的区别 PHP中echo和print的功能基本相同(输出),但是两者之间还是有细微差别的。echo输出后没有返回值,但print有返回值,当其执行失败时返回fla...

php对xml文件的增删改查操作实现方法分析

本文实例讲述了php对xml文件的增删改查操作实现方法。分享给大家供大家参考,具体如下: xml源文件 <?xml version="1.0" encoding="ut...