Home >Backend Development >PHP Tutorial >Solution to gbk Chinese garbled code passed by PHP array to JavaScript and json_encode_PHP tutorial
The article introduces the solution to gbk Chinese garbled characters when PHP arrays are passed to JavaScript and json_encode. The following is the creation of a JSON function. This paragraph comes from a hero on the Internet
The code is as follows | Copy code | ||||||||
* * Use a specific function to process all elements in the array * @param string &$array The string to be processed * @param string $function The function to be executed * @return boolean $apply_to_keys_also Whether to also apply to keys * @access public * *************************************************** ***********/ function arrayRecursive(&$array, $function, $apply_to_keys_also = false) { foreach ($array as $key => $value) { if (is_array($value)) { 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]); } } } }
* * Convert array to JSON string (compatible with Chinese) * @param array $array The array to be converted * @return string The converted json string * @access public * *************************************************** ***********/ function JSON($array) { arrayRecursive($array, 'urlencode', true); $json = json_encode($array); Return urldecode($json); } |
The code is as follows | Copy code |
$dbcnx = @mysql_connect ( "localhost", "root", "1234" ); if (! $dbcnx) { echo ("Unable to connect to the " . "database server at this time."); exit (); } if (! @mysql_select_db ( "pms" )) { echo ("Unable to locate the joke " . "database at this time."); exit (); } mysql_query ( "SET NAMES 'GB2312'" ); $q=mysql_query("select * from ability where ALV = 1"); While($row=mysql_fetch_array($q)){ $array1[] = $row[AName]; } |
The array array1 is passed to JavaScript to the array ability1
The code is as follows
|
Copy code
class myClass { 程序输出结果: {"item1":1,"item2":"u4e2du6587"} |