The php json_encode of function returns the json data instance code

  • 2021-07-21 08:01:51
  • OfStack

Usage of the json_encode () function.

echo json_encode(array('a'= > 'bbbb','c'= > 'ddddd');

This will generate 1 data in standard json format

The code is as follows


<?php

// What needs to be executed SQL Statement 
// Single strip 
$sql="select id,name from tbl_user where id=1";
// Multiple pieces of data 
//$sql="select id,name from tbl_user";

// Call conn.php File for database operation 
require('Conn.php');

// Prompt operation success information, note: $result Exist in conn.php In the file, it 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));

*/

/* Single data */

$row=mysql_fetch_row($result,MYSQL_ASSOC);

echo json_encode(array('jsonObj'=>$row));
}

mysql_free_result($result);
// Release results 
mysql_close();
// Close the connection 

?>

The above is the database generating json data

Single data: {"jsonObj": {"id": "1", "name": "lmw"}}

Multiple pieces of 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 result in Json format, such as:

The code is as follows


{
"UserKeyGetResponse":
{"RequestName":"e99e6d63e8c712d7699f52978a","api_key_value":"41954dd9b1cb6a95802eab6810"},
"error_response":
{"code":"NO_ERROR(www.ofstack.com)","msg":" Successful in obtaining system parameters "}
}

You can write the results as an array like this:

$respon = array('UserKeyGetResponse' => array('RequestName' => $api_request_name, 'api_key_value' => $api_key_value),
'error_response' => array('code' => 'NO_ERROR', 'msg' => ' Successful in obtaining system parameters '));

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 does not exist ');
echo JSON($array);

The results are:

{"code": "ERROR_MSG_MISS", "msg": "Message does not exist"}
The client can parse the result, of course, the error code should be replaced by numbers.

This is much better. What we show is Chinese directly. Of course, there is no problem in displaying the hexadecimal code.


Related articles: