The json_encode () built-in function (php52) in php can be used to transfer data in php well with other languages and use it, this function converts a value to a json data storage format.
The json_encode () built-in function (php> 5.2) in php can be used to transmit and use data in php with other languages, this function converts a value to a json data storage format.
- $ Arr = array ('a' => 1, 'B' => 2, 'C' => 3, 'D' => 4, 'E' => 5 );
- Echo json_encode ($ arr );
- // Result
- // {"A": 1, "B": 2, "c": 3, "d": 4, "e": 5}
The following describes a json_encode Chinese garbled problem:
The solution is to use the urlencode () function to process the following. before json_encode, urlencode () is used to process all the content in the array, and json_encode () is used to convert the content into a json string, finally, use urldecode () to convert the encoded Chinese characters back.
- 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 )){
- 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 --;
- }
-
- /*************************************** ***********************
- *
- * Convert an array to a json string (compatible with Chinese characters)
- * @ 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 );
- }
- $ Array = array
- (
- 'Name' => 'chia ',
- 'Age' => 20
- );
- Echo json ($ array );
Application instance:
- $ Servname = "localhost ";
- $ Sqlservname = "root ";
- $ Sqlservpws = "123456 ";
- $ Sqlname = "lock1 ";
- $ Db = mysql_connect ($ servname, $ sqlservname, $ sqlservpws) or die ("database connection failed ");
- Mysql_select_db ($ sqlname, $ db );
- $ SQL = "select * from t_operater ";
- $ Result = mysql_query ($ SQL );
- $ Rows = mysql_num_rows ($ result );
- While ($ obj = mysql_fetch_object ($ result ))
- {
- $ Arr [] = $ obj;
- }
- Echo '({"total": "'. $ rows. '", "results":'. json_encode ($ arr ).'})';