php returns json
Jul 29, 2016 am 09:12 AM<?php include './include/conn.php'; //数据库链接文件 $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); ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title>第一php网提供的教程--将数据库读取的数据生成json格式</title> <meta http-equiv="Content-Type" c/html; charset=utf-8" /> <!-- <script src="http://<strong>ajax</strong>.googleapis.com/<strong>ajax</strong>/libs/jquery/1.4/jquery.min.js" type="text/javascript"/></script> --> <script language=javascript> </script> </head> <body> <pre> <h1>请注意两种方法生成的对象数组在结构上的区别</h1> <?php echo '<h1>法一</h1>'; //假设以下数组是根据我们从数据库读取的数据生成的 $jarr=array('total'=>239,'row'=>array( array('code'=>'001','name'=>'中国','addr'=>'Address 11','col4'=>'col4 data'), array('code'=>'002','name'=>'Name 2','addr'=>'Address 12','col4'=>'col4 data'), ) ); //法一: $jobj=new stdclass();//实例化stdclass,这是php内置的空类,可以用来传递数据,由于json_decode后的数据是以对象数组的形式存放的, //所以我们生成的时候也要把数据存储在对象中 foreach($jarr as $key=>$value){ $jobj->$key=$value; } print_r($jobj);//打印传递属性后的对象 echo '使用$jobj->row[0][\'code\']输出数组元素:'.$jobj->row[0]['code'].'<br>'; echo '编码后的<strong>json字符串</strong>:'.json_encode($jobj).'<br>';//打印编码后的<strong>json字符串</strong> echo '<hr>'; //法二: echo '<h1>法二</h1>'; echo '编码后的<strong>json字符串</strong>:'; echo $str=json_encode($jarr);//将数组进行json编码 echo '<br>'; $arr=json_decode($str);//再进行json解码 print_r($arr);//打印解码后的数组,数据存储在对象数组中 echo '使用$arr->row[0]->code输出数组元素:'.$arr->row[0]->code; ?> </body> </html>
The above introduces how PHP returns json, including ajax and json string content. I hope it will be helpful to friends who are interested in PHP tutorials.

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

What are the differences between Huawei GT3 Pro and GT4?

Combination of golang WebSocket and JSON: realizing data transmission and parsing

What is the difference between MySQL5.7 and MySQL8.0?

How to exclude a field from JSON using @Expose annotation in Java?

Performance optimization tips for converting PHP arrays to JSON

Use the json.MarshalIndent function in golang to convert the structure into a formatted JSON string

Pandas usage tutorial: Quick start for reading JSON files

How to handle XML and JSON data formats in C# development
