There are two methods to save an array of numbers to a field in the database. One is to use the serialize ($ arr) serialization function ); another method is to use the json extension built-in function json_encode ($ arr) of php. If json_encode encodes Chinese characters, it is automatically converted to unicode encoding. Like this: a: 2: {s: 4: "code"; s: 1: "1 & Prime; s: 3:" msg "; s: 9: "PHP log" ;}, although JavaScript can be processed normally, it still looks not so good. Find a function on the official PHP website to solve this problem, that is, data is converted to json, and Chinese characters are not converted to unicode codes.
The code is as follows: |
Copy code |
<? Php Function php2js ($ a = false) { If (is_null ($ a) return 'null '; If ($ a = false) return 'false '; If ($ a = true) return 'true '; If (is_scalar ($ )) { If (is_float ($ )) { // Always use "." for floats. $ A = str_replace (",", ".", strval ($ )); }
// All scalars are converted to strings to avoid indeterminism. // PHP's "1" and 1 are equal for all PHP operators, // JS's "1" and 1 are not. So if we pass "1" or 1 from the PHP backend, // We shocould get the same result in the JS frontend (string ). // Character replacements for JSON. Static $ jsonReplaces = array ("", "/", "n", "t", "r", "B", "f ",'"'), Array ('\', '/', 'n', 'T', 'R', 'B', 'F ','"')); Return '"'. str_replace ($ jsonReplaces [0], $ jsonReplaces [1], $ ).'"'; } $ IsList = true; For ($ I = 0, reset ($ a); $ I <count ($ a); $ I ++, next ($ )) { If (key ($ )! == I I) { $ IsList = false; Break; } } $ Result = array (); If ($ isList) { Foreach ($ a as $ v) $ result [] = php2js ($ v ); Return '['. join (',', $ result). ']'; } Else { Foreach ($ a as $ k => $ v) $ result [] = php2js ($ k). ':'. php2js ($ v ); Return '{'. join (',', $ result ).'}'; } } ?> |
Method 1:
Echo serialize (array ('code' => '1 & prime;, 'MSG '=> 'php log '));
Output: a: 2: {s: 4: "code"; s: 1: "1 & Prime; s: 3:" msg "; s: 9: "PHP log ";}
Method 2:
Echo json_encode (array ('code' => '1 & prime;, 'MSG '=> 'php log '));
Output: {"code": "1 & Prime;," msg ":" PHPu65e5u5fd7 & Prime ;}
Method 3:
Echo php2js (array ('code' => '1 & prime;, 'MSG '=> 'Unknown error '));
Output: {"code": "1", "msg": "PHP log "}