PHP 提取数据库数据并转化为二维 json 的方法
首先贴一段示例代码:
- <?php
- include "con_db.php";//连接数据库
- $sql="select * from note order by note_date desc limit ".($index*10).",10"; //sql语句
- $result=mysql_query($sql);//获得结果
- $note;$i=0; //初始化变量
- while($infor=mysql_fetch_array($result))
- {
- //把结果放到一个一维数组里
- $note["id"]=$infor['note_id'];
- $note["content"]=$infor['note_content'];
- $note["date"]=$infor['note_date'];
- $note["username"]=$infor['username'];
- //放到二维数组里
- $notes[$i++]=$note;
- }
- echo json_encode($notes );
- ?>
-
输出结果:
- [{"id":"12","content":"u662f","date":"2014-05-24 09:31:52","username":"u532f"},
- {"id":"31","content":"u642f","date":"2014-05-24 09:31:49","username":"u322f"},
- {"id":"70","content":"u692f","date":"2014-05-24 09:31:48","username":"u132f"}]
-
你会发现应该输出的汉字变成了 unicode 字符集.
这时我们就要用到 urlencode 的方法,把汉字用 urlencode 方法编码,转化为 json 之后再用 urldecode 解码。看如下例子:
- <?php
- $h =urlencode("开心");
- echo $h;
- $x =urldecode($h);
- echo $x;
- ?>
-
输出结果:
- %BF%AA%D0%C4开心
-
这样通过中间过程的编码和解码,转化成 json 的过程便不会自动把汉字变成 Unicode 字符集了。所以最后的方法为:
- <?php
- while($infor=mysql_fetch_array($re))
- {
- $note["id"]=$infor['note_id'];//数字不需要编码
- $note["content"]=urlencode($infor['note_content']);//汉字需要编码
- $note["date"]=$infor['note_date'];
- $note["username"]=urlencode($infor['username']);
- $notes[$i++]=$note;
- }
- echo urldecode(json_encode($notes ));//转化成json之后再用urldecode解码为汉字
- ?>
-
结果如下:
- [{"id":"22","content":"文章","date":"2014-05-24 09:31:52","username":"王"},
- {"id":"21","content":"内容","date":"2014-05-24 09:31:49","username":"李"},
- {"id":"20","content":"可以","date":"2014-05-24 09:31:48","username":"冯"}]
-
这样我们就成功地把二维数组转化成了 json 了.