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程序设计有所帮助。

相关文章

支持生僻字且自动识别utf-8编码的php汉字转拼音类

拼音类文件py_class.php源码如下: <?php class py_class{ function py_class(){ $this ->...

php判断数组元素中是否存在某个字符串的方法

方法一:采用in_array(value,array,type) type 可选。如果设置该参数为 true,则检查搜索的数据与数组的值的类型是否相同。 复制代码 代码如下:$arr...

php导出excel格式数据问题

解决2个问题:1.身份证之类的文本数据自动转为科学计数法的问题。2.中文乱码的问题 excel从web页面上导出的原理。当我们把这些数据发送到客户端时,我们想让客户端程序(浏览器)以ex...

PHP中if和or运行效率对比

本文实例讲述了PHP中if和or运行效率对比。分享给大家供大家参考。具体实现方法如下: 对if和or的运行效率进行了实例说明,感兴趣的朋友可以测试一下,这里我测试了的结果是or 比if效...

PHP测试成功的邮件发送案例

mail()函数的作用:连接到邮件服务器,利用smtp协议,与该服务器交互并投邮件。 注意: 1、mail函数不支持esmtp协议,---即,只能直投,不能登陆 2、由上条,我们只能直投...