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

相关文章

详解WordPress中简码格式标签编写的基本方法

WordPress 简码是一种类似于论坛标签的东西,格式类似于把尖括号换成中括号的 Html 标签。简码很多人叫做短代码,但官方的翻译应该是简码,在这里纠正一下。 简码的开发的逻辑比较简...

Warning: session_destroy() : Trying to destroy uninitialized sessionq错误

经查证,在进行使用session_destroy()函数必须先调用session_start()函数。 也就是要有如下代码: 复制代码 代码如下: <? session_start...

PHP MemCached 高级缓存应用代码

Memcache常用方法 Memcache::add — 添加一个值,如果已经存在,则返回false Memcache::addServer — 添加一个可供使用的服务器地址 Memca...

PHP中imagick函数的中文解释

imagick的:: adaptiveBlurImage - 增加了自适应模糊滤镜图像  imagick的:: adaptiveResizeImage - 自适应调整图像数据...

Discuz!下Memcache缓存实现方法

前言:在PHP+MySQL架构的站点中,本文重点从MySQL的角度去分析如何使Discuz!论坛(或者类似的PHP+MySQL架构的程序)应对大访问量。同时给出一些使用Memcache去...