Value: The value to be encoded. This function only applies to UTF-8 encoded data.
Options: This optional value is a bitmask consisting of JSON_HEX_TAG JSON_HEX_QUOT, JSON_HEX_AMP, JSON_HEX_APOS, JSON_NUMERIC_CHECK, JSON_PRETTY_PRINT, JSON_UNESCAPED_SLASHES, JSON_FORCE_OBJECT
Example
The following example demonstrates how to convert an array to JSON using PHP:
include './include/conn.php'; //Database link file
$sql_notice = mysql_query('SELECT * FROM gg_notice where enable = "1" limit 0,10');
$notice = mysql_fetch_array($sql_notice, MYSQL_ASSOC);
print_r ($notice);
?>
Tutorial provided by the first php website - Generate json format from data read from the database
Please note the structural difference between the object arrays generated by the two methods
echo '
法一
';
//Assume that the following array is generated based on the data we read from the database
$jarr=array('total'=>239,'row'=>array(
array('code'=>'001','name'=>'China www.111cn.net','addr'=>'Address 11','col4'=>'col4 data'),
array('code'=>'002','name'=>'Name 2','addr'=>'Address 12','col4'=>'col4 data'),
)
);
//Method 1:
$jobj=new stdclass();//Instantiate stdclass, which is an empty class built into PHP and can be used to transfer data. Since the data after json_decode is stored in the form of an object array,
//So when we generate it, we also need to store the data in the object
foreach($jarr as $key=>$value){
$jobj->$key=$value;
}
print_r($jobj);//Print the object after passing the attributes
echo 'Use $jobj->row[0]['code'] to output array elements:'.$jobj->row[0]['code'].' ';
echo 'Encoded json string:'.json_encode($jobj).' ';//Print the encoded json string
echo '
';
//Method 2:
echo '
Method 2
';
echo 'Encoded json string:';
echo $str=json_encode($jarr);//Encode the array into json
echo ' ';
$arr=json_decode($str);//Decode json again
print_r($arr);//Print the decoded array, the data is stored in the object array
echo 'Use $arr->row[0]->code to output array elements:'.$arr->row[0]->code;
?>
http://www.bkjia.com/PHPjc/733189.htmlwww.bkjia.comtruehttp: //www.bkjia.com/PHPjc/733189.htmlTechArticleEncoding JSON in PHP (json_encode) The PHP json_encode() function is used to encode JSON in PHP. This function returns the value represented by JSON on success, or FALSE on failure. Syntax: string json_encode ( $va...
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn