Json_encode () function usage.
Echo json_encode (array ('a' => 'bbbbb', 'C' => 'ddddd ');
In this way, a standard json format data is generated.
The code is as follows: |
Copy code |
<? Php // SQL statement to be executed // Single $ SQL = "select id, name from tbl_user where id = 1 "; // Multiple data entries // $ SQL = "select id, name from tbl_user "; // Call the conn. Php file for database operations Require ('Conn. Php '); // Message indicating successful operation. Note: $ result exists in the conn. Php file and is called. If ($ result) { // $ Array = mysql_fetch_array ($ result, MYSQL_ASSOC ); /* Dataset $ Users = array (); $ I = 0; While ($ row = mysql_fetch_array ($ result, MYSQL_ASSOC )){ Echo $ row ['id']. '-----------'. $ row ['name']. '</br> '; $ Users [$ I] = $ row; $ I ++; } Echo json_encode (array ('datalist' => $ users )); */ /* Single data entry */ $ Row = mysql_fetch_row ($ result, MYSQL_ASSOC ); Echo json_encode (array ('jsonobj '=> $ row )); } Mysql_free_result ($ result ); // Release result Mysql_close (); // Close the connection ?> |
The above is the json data generated by the database.
Single data entry: {"jsonObj": {"id": "1", "name": "lmw "}}
Multiple data entries: {"dataList": [{"id": "1", "name": "lmw" },{ "id": "2 ", "name": "xxj" },{ "id": "3", "name": "xxxj"}]}
In many cases, the program needs to return a result in Json format, for example:
The code is as follows: |
Copy code |
{ "UserKeyGetResponse ": {"RequestName": "e99e6d63e8c712d7699f52978a", "api_key_value": "41954dd9b1cb6a95802eab6810 "}, "Error_response ": {"Code": "NO_ERROR", "msg": "system parameter retrieved "} } You can write the result as an array: $ Respon = array ('userkeygetresponse' => array ('requestname' => $ api_request_name, 'api _ key_value '=> $ api_key_value ), 'Error _ response' => array ('code' => 'No _ error', 'MSG '=> 'system parameter Retrieved successfully ')); |
Code
The code is as follows: |
Copy code |
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 --; } |
G:
$ Error_respon = array ('code' => 'Error _ MSG_MISS ', 'MSG' => 'message nonexistent ');
Echo JSON ($ array );
Result:
{"Code": "ERROR_MSG_MISS", "msg": "The message does not exist "}
The client can parse this result. Of course, the error code should be replaced by a number.
This is much better. We can display Chinese characters directly. Of course, it is okay to display the hexadecimal encoding.