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 正则学习实例

"^The": 匹配以 "The"开头的字符串;    "of despair$": 匹配以 "of despair...

php设置静态内容缓存时间的方法

本文实例讲述了php设置静态内容缓存时间的方法。分享给大家供大家参考。具体方法分析如下: 在利用百度工具作一个小测试时提示我们需要设置静态内容缓存时间了,我自己没有服务器权限操作,只能从...

深入解析PHP中的(伪)多线程与多进程

(伪)多线程:借助外力利用WEB服务器本身的多线程来处理,从WEB服务器多次调用我们需要实现多线程的程序。QUOTE:我们知道PHP本身是不支持多线程的, 但是我们的WEB服务器是支持多...

PHP内部实现打乱字符串顺序函数str_shuffle的方法

PHP内部实现打乱字符串顺序函数str_shuffle的方法

前言 2019年春节已过,今天是上班第一天,还得翻一翻之前没有看完的PHP源码。 今天聊的是字符串顺序打乱函数str_shuffle。这个函数本身使用频率并不高。但是,其内部实现还是非常...

php模拟post行为代码总结(POST方式不是绝对安全)

这里提供两种方法供选择:第一:手写代码。第二:利用HttpClient php类库   第一种方法: 复制代码 代码如下: <?PHP $flag = 0; //要post的数据...