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文件操作小结(删除指定文件/获取文件夹下的文件名/读取文件夹下图片名)

本文实例分析了php文件操作的方法。分享给大家供大家参考,具体如下: 一、删除文件 unlink() 语法: int unlink(string filename); 返回值: 整数 函...

ThinkPHP 表单自动验证运用示例

使用TP 3.2框架 public function add_post(){ //验证规则 $rule=array( array('name','require','请输入姓名',...

PHP结合Ueditor并修改图片上传路径

PHP结合Ueditor并修改图片上传路径

前言 在使用UEditor编辑器时,一般我们都是需要修改默认的图片上传路径的,下面是我整理好的修改位置和方法供大家参考。 操作 Ueditor PHP版本本身自带了一套上传程序,我们...

php事务回滚简单实现方法示例

本文实例讲述了php事务回滚简单实现方法。分享给大家供大家参考,具体如下: $servername="localhost"; $username="root"; $password=...

PHP基于PDO实现的SQLite操作类【包含增删改查及事务等操作】

本文实例讲述了PHP基于PDO实现的SQLite操作类。分享给大家供大家参考,具体如下: 直接代码: 注意:一定要写好数据库保存路径 <?php // sqlite分页...