码迷,mamicode.com
首页 > Web开发 > 详细

json_encode替代函数

时间:2015-06-17 08:14:46      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:

<?php
 
function jsonEncode($var) {
    if (function_exists(‘json_encode‘)) {
        return json_encode($var);
    else {
        switch (gettype($var)) {
            case ‘boolean‘:
                return $var ‘true‘ ‘false‘// Lowercase necessary!
            case ‘integer‘:
            case ‘double‘:
                return $var;
            case ‘resource‘:
            case ‘string‘:
                return ‘"‘str_replace(array("\r", "\n", "<", ">", "&"),
                    array(‘\r‘‘\n‘‘\x3c‘‘\x3e‘‘\x26‘),
                    addslashes($var)) .‘"‘;
            case ‘array‘:
                // Arrays in JSON can‘t be associative. If the array is empty or if it
                // has sequential whole number keys starting with 0, it‘s not associative
                // so we can go ahead and convert it as an array.
                if (empty ($var) || array_keys($var) === range(0, sizeof($var) - 1)) {
                    $output array();
                    foreach ($var as $v) {
                        $output[] = jsonEncode($v);
                    }
                    return ‘[ ‘. implode(‘, ‘$output) .‘ ]‘;
                }
                // Otherwise, fall through to convert the array as an object.
            case ‘object‘:
                $output array();
                foreach ($var as $k => $v) {
                    $output[] = jsonEncode(strval($k)) .‘: ‘. jsonEncode($v);
                }
                return ‘{ ‘. implode(‘, ‘$output) .‘ }‘;
            default:
                return ‘null‘;
        }
    }
 
}
 
$arr=array(‘name‘=>‘CSDN论坛‘,‘degree‘=>‘numberone‘);
 
echo jsonEncode($arr);
 
?>

转载地址:http://blog.csdn.net/ktz666/article/details/7593040

json_encode替代函数

标签:

原文地址:http://www.cnblogs.com/songzhenghe/p/4582310.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!