php数组转成json格式的方法

yipeiwu_com5年前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简单smarty入门程序实例

本文实例讲述了php简单smarty入门程序。分享给大家供大家参考。具体如下: 首先要有3个文件夹configs、templates、templates_c,在configs文件夹中有一...

php图片添加文字水印实现代码

php类库给现有的图片加文字水印,代码不是很完善,欢迎大家多多指教!代码如下: <?php /*PHP图片加文字水印类库 QQ:3697578482 伤心的歌 该类库...

学习php设计模式 php实现状态模式

学习php设计模式 php实现状态模式

一、意图 允许一个对象在其内部状态改变时改变它的行为。对象看起来似乎修改了它的类 状态模式变化的位置在于对象的状态 二、状态模式结构图   三、状态模式中主要角色 抽象状态...

php解析json数据实例

本文以实例形式展示了php解析json数据的方法,这是一个比较实用的功能,分享给大家供大家参考。具体代码如下: <?php $data; $data.= "["; fo...

PHP提示Warning:phpinfo() has been disabled函数禁用的解决方法

本文实例讲述了PHP提示Warning:phpinfo() has been disabled函数禁用的解决方法。分享给大家供大家参考。具体分析如下: 今天在一朋友服务器测试一个网站时发...