php5.2 json,php5.2以上版本json_encode兼容性

php5.2以下版本json_encode兼容性

php5.1版本通过编译加载的json.so,在使用json_encode时会把键名为空的数组

$arr =array(''=>array('id'=>'aaa','total'=>'bbb'))转化成空;但是在php5.2中使用使用自带的此函数不存在此问题。

或者不想编译加载json.so扩展,可以使用替代函数

$jsonencode = version_compare(PHP_VERSION, '5.2.5', '>=') ? json_encode($arr) : php_json_encode($arr);

echo $jsonencode;

function php_json_encode($arg) {

$returnValue = '';

$c = '';

$i = '';

$l = '';

$s = '';

$v = '';

$numeric = true;

switch (gettype($arg)) {

case 'array':

foreach ($arg AS $i => $v) {

if (!is_numeric($i)) {

$numeric = false;

break;

}

}

if ($numeric) {

foreach ($arg AS $i => $v) {

if (strlen($s) > 0) {

$s .= ',';

}

$s .= json_encode($arg[$i]);

}

$returnValue = '[' . $s . ']';

} else {

foreach ($arg AS $i => $v) {

if (strlen($s) > 0) {

$s .= ',';

}

$s .= json_encode($i) . ':' . json_encode($arg[$i]);

}

$returnValue = '{' . $s . '}';

}

break;

case 'object':

foreach (get_object_vars($arg) AS $i => $v) {

$v = json_encode($v);

if (strlen($s) > 0) {

$s .= ',';

}

$s .= json_encode($i) . ':' . $v;

}

$returnValue = '{' . $s . '}';

break;

case 'integer':

case 'double':

$returnValue = is_numeric($arg) ? (string) $arg : 'null';

break;

case 'string':

$returnValue = '"' . strtr($arg, array(

"\r" => '\\r', "\n" => '\\n', "\t" => '\\t', "\b" => '\\b',

"\f" => '\\f', '\\' => '\\\\', '"' => '\"',

"\x00" => '\u0000', "\x01" => '\u0001', "\x02" => '\u0002', "\x03" => '\u0003',

"\x04" => '\u0004', "\x05" => '\u0005', "\x06" => '\u0006', "\x07" => '\u0007',

"\x08" => '\b', "\x0b" => '\u000b', "\x0c" => '\f', "\x0e" => '\u000e',

"\x0f" => '\u000f', "\x10" => '\u0010', "\x11" => '\u0011', "\x12" => '\u0012',

"\x13" => '\u0013', "\x14" => '\u0014', "\x15" => '\u0015', "\x16" => '\u0016',

"\x17" => '\u0017', "\x18" => '\u0018', "\x19" => '\u0019', "\x1a" => '\u001a',

"\x1b" => '\u001b', "\x1c" => '\u001c', "\x1d" => '\u001d', "\x1e" => '\u001e',

"\x1f" => '\u001f'

)) . '"';

break;

case 'boolean':

$returnValue = $arg?'true':'false';

break;

default:

$returnValue = 'null';

}

return $returnValue;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值