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开发中AJAX技术的简单应用

AJAX无疑是2005年炒的最热的Web开发技术之一,当然,这个功劳离不开Google。我只是一个普通开发者,使用AJAX的地方不是特别多,我就简单的把我使用的心得说一下。(本文假设用户...

PHP简单预防sql注入的方法

本文实例讲述了PHP简单预防sql注入的方法。分享给大家供大家参考,具体如下: 出现sql注入一般都是因为语法不规范不严谨造成的,问题出现在sql语句上,而起决定性的是quote(')。...

php编写一个简单的路由类

类代码:复制代码 代码如下: <?php class Router { public function getRouter($types = 1) { if ( isset($_S...

PHP字符串中插入子字符串方法总结 原创

本文实例讲述了PHP字符串中插入子字符串方法。分享给大家供大家参考,具体如下: 首先来看看一个网上常见的方法: 方法一:字符串遍历 function str_insert($str,...

redis 队列操作的例子(php)

入队操作 复制代码 代码如下: <?php $redis = new Redis(); $redis->connect('127.0.0.1',6379); while(Tr...