dodgepudding/wechat-php-sdk — pull request #158 by binsee (2014-11-27 08:12:25+00:00)
Title: 修复json_encode方法bug

当传入数组内值为数字字符串，会被作为数字处理，在某些时候可能会引起错误。
如测试数组：
```php
$arr = array(
"str"=>"12345",
"zh"=>"“中文测试”",
"int"=>201,
"t"=>true,
"f"=>false,
"ts"=>1,
"arr"=>array(
"int"=>101,
"textint"=>"102",
"cn"=>"测试"
)
);
```

php5.4以后，原生的json_encode增加了一个选项，可以直接避免中文被转码，如：
```php
json_encode($arr,JSON_UNESCAPED_UNICODE)
```

使用以前的代码，与原生json_encode使用JSON_UNESCAPED_UNICODE的输出结果对比：
```
string(121) "{"str":12345,"zh":"“中文测试”","int":201,"t":true,"f":false,"ts":1,"arr":{"int":101,"textint":102,"cn":"测试"}}"
string(125) "{"str":"12345","zh":"“中文测试”","int":201,"t":true,"f":false,"ts":1,"arr":{"int":101,"textint":"102","cn":"测试"}}"
```

可以看到字符串形式的数字，在生成的json里，被作为数字生成了。这样会再某些时候可能导致问题
对类内的json_encode进行修复，再测试结果：
```
string(125) "{"str":"12345","zh":"“中文测试”","int":201,"t":true,"f":false,"ts":1,"arr":{"int":101,"textint":"102","cn":"测试"}}"
string(125) "{"str":"12345","zh":"“中文测试”","int":201,"t":true,"f":false,"ts":1,"arr":{"int":101,"textint":"102","cn":"测试"}}"
```

完整测试代码：
```
$value ) {
if (is_array ( $value )) { //Custom handling for arrays
if ($is_list)
$parts [] = json ( $value ); /* :RECURSION: */
else
$parts [] = '"' . $key . '":' . json ( $value ); /* :RECURSION: */
} else {
$str = '';
if (! $is_list)
$str = '"' . $key . '":';
//Custom handling for multiple data types
if (!is_string ( $value ) && is_numeric ( $value ) && $value<2000000000)
$str .= $value; //Numbers
elseif ($value === false)
$str .= 'false'; //The booleans
elseif ($value === true)
$str .= 'true';
else
$str .= '"' . addslashes ( $value ) . '"'; //All other things
// :TODO: Is there any more datatype we should be in the lookout for? (Object?)
$parts [] = $str;
}
}
$json = implode ( ',', $parts );
if ($is_list)
return '[' . $json . ']'; //Return numerical JSON
return '{' . $json . '}'; //Return associative JSON
}
$arr = array(
"str"=>"12345",
"zh"=>"“中文测试”",
"int"=>201,
"t"=>true,
"f"=>false,
"ts"=>1,
"arr"=>array(
"int"=>101,
"textint"=>"102",
"cn"=>"测试"
)
);
$ret =json($arr);
var_dump($ret);
echo "
";
echo "
";
$ret=json_encode($arr,JSON_UNESCAPED_UNICODE);
var_dump($ret);
echo "
";
echo "
";
var_dump($arr);
?>
```