Created
February 27, 2014 06:18
-
-
Save hubsgz/9245330 to your computer and use it in GitHub Desktop.
中文不会被转换成 \uxxxx 形式 的 json_encode 代码
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class JSON | |
{ | |
/** | |
* 使用特定function对数组中所有元素做处理 | |
* | |
* @param string &$array 要处理的字符串 | |
* @param string $function 要执行的函数 | |
* @param boolean $apply_to_keys_also 是否也应用到key上 | |
* | |
* @return null | |
**/ | |
public function arrayRecursive(&$array, $function, $apply_to_keys_also = false) | |
{ | |
static $recursive_counter = 0; | |
if (++$recursive_counter > 1000) { | |
die('possible deep recursion attack'); | |
} | |
foreach ($array as $key => $value) { | |
if (is_array($value)) { | |
$this->arrayRecursive($array[$key], $function, $apply_to_keys_also); | |
} else { | |
$array[$key] = $function($value); | |
} | |
if ($apply_to_keys_also && is_string($key)) { | |
$new_key = $function($key); | |
if ($new_key != $key) { | |
$array[$new_key] = $array[$key]; | |
unset($array[$key]); | |
} | |
} | |
} | |
$recursive_counter--; | |
} | |
/** | |
* 将数组转换为JSON字符串(兼容中文) | |
* | |
* @param array $array 要转换的数组 | |
* | |
* @return string 转换得到的json字符串 | |
* @access public | |
*/ | |
public function encode($array) | |
{ | |
$this->arrayRecursive($array, 'urlencode', true); | |
$json = json_encode($array); | |
return urldecode($json); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
$recursive_counter
should be set on the class not inside the function so that the class can be used multiple times without it filling up.