Json_encode () function usage.
echo json_encode (Array (' A ' => ' bbbb ', ' C ' => ' ddddd ');
This will generate a standard JSON-formatted data
The code is as follows
<?php
//SQL statement/single
$sql = "Select Id,name from Tbl_user where id=1";
Multiple data
//$sql = "Select Id,name from Tbl_user";
Call conn.php file for database operation
require (' conn.php ');
Prompt Operation success Information, note: $result exists in conn.php file, is called out
if ($result)
{
//$array =mysql_fetch_array ($result, MySQL _ASSOC);
/* Data Set
$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));
* *
////////* $row =mysql_fetch_row ($result, MYSQL_ASSOC);
echo json_encode (Array (' Jsonobj ' => $row));
}
Mysql_free_result ($result);
Release result
mysql_close ();
Close Connection
?>
This is the database generating JSON data.
Single data: {"Jsonobj": {"id": "1", "name": "LMW"}}
More than one data: {"DataList": [{"id": "1", "name": "LMW"},{"id": "2", "Name": "XXJ"},{"id": "3", "Name": "Xxxj"}]}
Now in many cases, we need the program to return a JSON-formatted result, such as:
The code is as follows
Copy Code code as follows:
{
"Userkeygetresponse":
{"Requestname": "e99e6d63e8c712d7699f52978a", "Api_key_value": "41954dd9b1cb6a95802eab6810"},
"Error_response":
{"Code": "No_error (www.jb51.net)", "MSG": "Get System parameters succeeded"}
}
You can write the results in such an array form:
Copy Code code as follows:
$respon = Array (' Userkeygetresponse ' => array (' Requestname ' => $api _request_name, ' api_key_value ' => $api _key_ Value),
' Error_response ' => Array (' Code ' => ' No_error ', ' msg ' => ' Get system Parameters succeeded '));
Code
Copy Code code as follows:
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 does not exist ');
echo JSON ($array);
The results are:
{"Code": "Error_msg_miss", "MSG": "Message does not exist"}
The client can parse this result, and of course the error code should be replaced with a number.
It's much better. We show the direct Chinese, of course, the 16 coding is also no problem.